How to Count Rows in PHP PDO
PDO, the industry-standard library for accessing databases in PHP, lacks a dedicated method for counting rows returned by SELECT queries. A common workaround is to utilize count($results->fetchAll()), but it's not always the most efficient approach.
PDOStatement::rowCount
The PDO statement object exposes a rowCount method. However, according to the official 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 with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
Counting Rows with Existing Recordset
If you have already fetched the data, you can use the count function on the result array:
$stmt = $db->prepare('SELECT * FROM table'); $stmt->execute(); $rowCount = count($stmt->fetchAll(PDO::FETCH_ASSOC));
Alternatively, you can rely on object-oriented traversal and count the rows manually:
$rowCount = 0; while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $rowCount++; }
Remember that fetching all rows into memory can impact application performance, especially with large result sets. Consider pagination or other optimization techniques as needed.
The above is the detailed content of How to Efficiently Count Rows from a PDO SELECT Statement in PHP?. For more information, please follow other related articles on the PHP Chinese website!