Counting results with PDO
Many developers asked me how I count the result rows from a PDO statement.
I asked them how they do it.
They answered me the following example of www.php.net:
<?php
$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) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
In some projects who I deployed recently I used the following code to count the rows:
<?phpMaybe you can use this simple lines of code yourself. Good luck with it.
$sQuery = "SELECT * FROM table";
$rResult = $pdo->query($sQuery)->fetchAll();
echo count($rResult);
?>
(4 votes)
- Login or register to post comments
- 2214 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)










Comments
knalli replied on Mon, 2009/02/16 - 6:03am
linusnorton replied on Fri, 2009/03/27 - 5:56am
What about
$stmt->rowCount();
This article
http://www.phpbuilder.com/manual/en/function.pdostatement-rowcount.php
Says some databases don't provide this for SELECT statements but it's never been an issue for me.
Philippe Lhoste replied on Tue, 2009/04/07 - 6:09am
in response to: knalli
alpha1125 replied on Sat, 2009/05/09 - 9:20pm
This way will break for large sets of data.
If you have a large data set, you run out of ram, and your script drops dead.
I suggest that you run the sql statement to do a count() on the database itself to get the actual count, and run the query again with a limit to get what you need.
bet replied on Tue, 2009/06/09 - 1:23pm