PHP PDO - alternative to mysqli_num_rows

With mysqli, I can get the number of rows from a select query using mysqli_num_rows. I can’t find a way to do this with PDO without having to make a separate request, for example SELECT COUNT(*)? I see no reason to make a separate request when I already have a set of records.

+4
source share
4 answers

You can use SQL_CALC_FOUND_ROWSas described here . For instance:

$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;

, LIMIT, , , COUNT(*), , , .

+4

Pdo rowCount. : $string-> rowCount ();

0

:

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

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

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

PDOStatement::rowCount() , SELECT. PDO:: query() SELECT COUNT (*) SELECT, PDOStatement:: fetchColumn(), , . .

$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) {
        /*    .... */

PHP.net, .

PDO num_rows?

You may think that having 2 queries is slower, but that is not the case. PDO is a common client library for several database systems, not just MySQL. For performance reasons, everys database system does not have internal, technical capabilities to calculate common strings in the selection of an uppon query. Knowing the total number of rows requires checking all rows before serving them.

0
source

All Articles