Counting Rows Efficiently with SELECT COUNT(*)
Instead of retrieving all rows from a table to determine the count, you can optimize the query by using SELECT COUNT(*). This query returns the number of rows without fetching the data.
To access the count value in PHP using this approach, you can't use the num_rows() method. Instead, use the following steps:
Here's an example:
$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt;
This code assigns the count value to the $count variable without fetching the actual data rows. By using this method, you improve query performance and reduce resource usage.
The above is the detailed content of How Can I Efficiently Count Database Rows in PHP Without Retrieving All Data?. For more information, please follow other related articles on the PHP Chinese website!