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: 
<?php 
$sQuery = "SELECT * FROM table";

$rResult = $pdo->query($sQuery)->fetchAll();
echo count($rResult);
?>
   Maybe you can use this simple lines of code yourself. Good luck with it.

 

1.75
Your rating: None Average: 1.8 (4 votes)

(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

Dear Marten, this is a nice joke, isn't it?

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

I hope so... :-)

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

My name is lucas, I have started my edveture with bookmakers 2 years ago.Since this time I have won around 100 000 usd. Would You like do same?? Think about Sports betting and change Your life. Nice post Regards

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.