Home > Database > Mysql Tutorial > How to Efficiently Get Row Counts Using SELECT COUNT(*) in PHP?

How to Efficiently Get Row Counts Using SELECT COUNT(*) in PHP?

Mary-Kate Olsen
Release: 2025-01-18 21:56:40
Original
281 people have browsed it

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>
Copy after login

Explanation of reasons

  • Rename the result column to cnt to avoid conflict with MySQL reserved words.
  • Use fetch_object() to get a single result object.
  • The
  • result object's cnt property contains the count value.

How to use

<code class="language-php">if ($count) {
  // 表中存在行。
}</code>
Copy after login

Other instructions

  • SELECT COUNT(*) returns a table with only one row and one column, and the column name is cnt.
  • Using 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template