简体   繁体   中英

PHP PDO - alternative for mysqli_num_rows

With mysqli I can get the number of rows from a select query by using mysqli_num_rows. I can't find a way to do that with PDO without having to do a separate query like SELECT COUNT(*) ? I don't see the point in doing a separate query when I already have a recordset.

You could use SQL_CALC_FOUND_ROWS as documented here . For example:

$result = $db->prepare("SELECT SQL_CALC_FOUND_ROWS id, name FROM fruit WHERE calories > 100"); 
$result->execute();
$result = $db->prepare("SELECT FOUND_ROWS()"); 
$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;

This option is normally used to get full match counts when you have a LIMIT clause, however, it works just fine without one, and it's much more efficient than issuing the same query again with a COUNT(*) since it just retrieves the count value stored by the first query value and does not have to run another full query.

In Pdo you use rowCount . Example: $string-> rowCount ();

try this:

$sql = "SELECT count(id) FROM `table` WHERE condition"; 
$result = $db->prepare($sql); 

$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;

RTM: http://php.net/manual/en/pdostatement.rowcount.php

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

  /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {
        /*    .... */

I don't want to copy the whole PHP.net page, please just read it.

Why does PDO not have num_rows ?

You may think it's slower to have 2 queries but it isn't. PDO is a general client library for several database systems, not only MySQL. For performance reasons, not everys database system has internal, technical ability to calculate the total rows in select uppon the query. Knowing the total number of rows requires to examine all rows before serving them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM