Viewed   364 times

There are many conflicting statements around. What is the best way to get the 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?


$sql = "SELECT count(*) FROM `table` WHERE foo = ?"; 
$result = $con->prepare($sql); 
$number_of_rows = $result->fetchColumn(); 

Not the most elegant way to do it, plus it involves an extra query.

PDO has PDOStatement::rowCount(), which apparently does not work in MySql. What a pain.

From the PDO Doc:

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.

EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:

$nRows = $pdo->query('select count(*) from blah')->fetchColumn(); 
echo $nRows;
Monday, September 12, 2022

The following works for me:


$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "pass");
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$stmt = $pdo->prepare("INSERT INTO `null_test` (`can_be_null`) VALUES (:null)");
$stmt->bindValue(":null", null, PDO::PARAM_NULL);


Pass in PHP's null, with type of PDO::PARAM_NULL. Also, make sure your prepare emulation is set to false. That might help.

Sunday, August 7, 2022

lastInsertId() is a method of the PDO class, not the PDOStatement class.

This should work:

$groupID = $dbo->lastInsertId();
Friday, November 18, 2022

using mysqli you do it the following way (assuming the mysqli object is already created -- you can also use the procedure methods, just slightly different):

$sql = "SELECT SQL_CALC_FOUND_ROWS *, as pid, bla bla 
        FROM account ORDER BY pid ASC". $eb["array"]['querylimit'];
$result = $mysqli->query($sql);
$TotalRcount = $result->num_rows;
    $col1 = $row['col1'];  // col1 is a placeholder for whatever column you are reading
    //read columns
Tuesday, September 13, 2022

you should replace

$rowCount = $query->rowCount();


$rowCount = $query->fetchColumn();

also, take a look at FOUND_ROWS()

there is no sense in calling fetch_num_rows 2 times, it is enough to do:

$numArticles = $rowCount = $article->fetch_num_rows();
Tuesday, November 15, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :