Home >Backend Development >PHP Tutorial >How to Efficiently Count Rows in a Database Table Using SQL and PHP?

How to Efficiently Count Rows in a Database Table Using SQL and PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 04:39:08597browse

How to Efficiently Count Rows in a Database Table Using SQL and PHP?

Getting the Count Using SELECT COUNT(*)

Instead of selecting all rows or a specific column, you may want to simply retrieve the count of rows in a specific table. Here's how you can do that using the SELECT COUNT(*) query:

Query Structure:

SELECT COUNT(*) AS count FROM cars

Retrieving the Count Value in PHP:

Since the result of the COUNT(*) query is a scalar value, representing the count of rows, you can retrieve it using the following code:

$count = $mysqli->query("SELECT COUNT(*) AS cnt FROM cars")->fetch_object()->cnt;

In this case, we avoid using the reserved word "count" for the column name by aliasing it as "cnt". By calling the fetch_object() method on the result object, we retrieve an anonymous object with a single property named "cnt". The value of this property represents the count of rows in the "cars" table.

Note: It's not recommended to use the keywords "count" or "cnt" as column names in SQL, as they are reserved words.

The above is the detailed content of How to Efficiently Count Rows in a Database Table Using SQL and PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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