Getting the row count using PDO in PHP can be achieved through various methods. However, the best approach depends on your specific use case and data size considerations.
If you require only the row count and not the data itself, using the "SELECT count(*)" query is recommended. Here's a code example:
$sql = "SELECT count(*) FROM `table` WHERE foo = ?"; $result = $con->prepare($sql); $result->execute([$bar]); $number_of_rows = $result->fetchColumn();
For scenarios where you need the number of rows along with the retrieved data, PDO provides the PDOStatement::rowCount() method. However, its reliability across different drivers is not guaranteed. As per the PDO documentation:
"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... then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned."
In such cases, you can use the PDO::fetchAll() function to retrieve the data into an array and then employ count() to determine the number of rows.
$data = $pdo->fetchAll(); $number_of_rows = count($data);
Alternatively, if your query is simple and doesn't utilize variables, you can use the query() function directly:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn(); echo $nRows;
The above is the detailed content of What's the Optimal Approach to Getting a Row Count with PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!