Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Counting results with PDO

DZone's Guide to

Counting results with PDO

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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.

 

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}