Row count with PDO

2018-12-31 03:57发布

There are many conflicting statements around. What is the best way to row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows.

fetchAll is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.

Do you have any suggestions?

标签: php mysql pdo
21条回答
时光乱了年华
2楼-- · 2018-12-31 04:25

As I wrote previously in an answer to a similar question, the only reason mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you.

So in PDO, your options are:

  1. Use MySQL's FOUND_ROWS() function.
  2. Use PDO's fetchAll() function to fetch all the rows into an array, then use count() on it.
  3. Do an extra query to SELECT COUNT(*), as karim79 suggested.
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 04:25

If you just want to get a count of rows (not the data) ie. using COUNT(*) in a prepared statement then all you need to do is retrieve the result and read the value:

$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$statement = $con->prepare($sql); 
$statement->execute(); 
$count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
return reset($count); // Resets array cursor and returns first value (the count)

Actually retrieving all the rows (data) to perform a simple count is a waste of resources. If the result set is large your server may choke on it.

查看更多
无色无味的生活
4楼-- · 2018-12-31 04:26

Have a look at this link: http://php.net/manual/en/pdostatement.rowcount.php It is not recommended to use rowCount() in SELECT statements!

查看更多
何处买醉
5楼-- · 2018-12-31 04:26

Use parameter array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL), else show -1:

Usen parametro array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL), sin ello sale -1

example:

$res1 = $mdb2->prepare("SELECT clave FROM $tb WHERE id_usuario='$username' AND activo=1 and id_tipo_usuario='4'", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$res1->execute();

$count=$res1->rowCount();
echo $count;
查看更多
美炸的是我
6楼-- · 2018-12-31 04:29

Answering this because I trapped myself with it by now knowing this and maybe it will be useful.

Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach. For example:

$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);           
if (count($rows) > 0) {             
    foreach ($rows as $row) {
        //output your rows
    }                       
}
查看更多
其实,你不懂
7楼-- · 2018-12-31 04:30

A quick one liner to get the first entry returned. This is nice for very basic queries.

<?php
$count = current($db->query("select count(*) from table")->fetch());
?>

Reference

查看更多
登录 后发表回答