Home > Backend Development > PHP Tutorial > How Can I Efficiently Count Database Rows in PHP Without Retrieving All Data?

How Can I Efficiently Count Database Rows in PHP Without Retrieving All Data?

DDD
Release: 2024-12-08 13:36:11
Original
921 people have browsed it

How Can I Efficiently Count Database Rows in PHP Without Retrieving All Data?

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:

  1. Execute the SELECT COUNT(*) as cnt query.
  2. Get the result of the query as an object using fetch_object().
  3. Access the value of the cnt property of the object.

Here's an example:

1

$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt;

Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template