Counting results with PDO
Join the DZone community and get the full member experience.
Join For FreeMany 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);
?>
Row (database)
dev
Opinions expressed by DZone contributors are their own.
Trending
-
Write a Smart Contract With ChatGPT, MetaMask, Infura, and Truffle
-
AI Technology Is Drastically Disrupting the Background Screening Industry
-
Mainframe Development for the "No Mainframe" Generation
-
DevOps Midwest: A Community Event Full of DevSecOps Best Practices
Comments