Home >Database >Mysql Tutorial >How to Efficiently Get Row Counts Using SELECT COUNT(*) in PHP?
*Use SELECT COUNT() efficiently in PHP to get the number of rows**
Direct SELECT all rows and then counting is inefficient. MySQL's SELECT COUNT(*) allows you to get the number of rows without retrieving the actual data.
Retrieve count value in PHP
To retrieve the count value from a SELECT COUNT(*) query, you cannot use $results->num_rows()
as this method only works when selecting actual data. The following methods should be used:
<code class="language-php">$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt;</code>
Explanation of reasons
cnt
to avoid conflict with MySQL reserved words. fetch_object()
to get a single result object. cnt
property contains the count value. How to use
<code class="language-php">if ($count) { // 表中存在行。 }</code>
Other instructions
cnt
. fetch_row()
or fetch_assoc()
instead of fetch_object()
will return an array with the count value at the first element. The above is the detailed content of How to Efficiently Get Row Counts Using SELECT COUNT(*) in PHP?. For more information, please follow other related articles on the PHP Chinese website!