Home > Database > Mysql Tutorial > body text

How to Count the Number of Rows Returned by a MySQL Query?

Mary-Kate Olsen
Release: 2024-11-03 20:39:29
Original
222 people have browsed it

How to Count the Number of Rows Returned by a MySQL Query?

Determining the Number of Rows Returned by a MySQL Query

Counting the number of rows returned by a MySQL query is essential for pagination, data analysis, and other scenarios. Here are various methods to achieve this:

Method 1: Using mysql_num_rows for Iterative Counting

For PHP applications, you can utilize the mysql_num_rows function to determine the number of rows in a result set. This function is exposed through the mysqli_num_rows function in PHP, as exemplified below:

<code class="php">$link = mysqli_connect("localhost", "user", "password", "database");

$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);

echo "$num_rows Rows\n";</code>
Copy after login

Method 2: COUNT(*) Function for Matching Criteria

To count the number of rows that meet specific criteria, use the COUNT(*) function in your query. For instance:

<code class="sql">SELECT COUNT(*) FROM foo WHERE bar='value';</code>
Copy after login

Method 3: SQL_CALC_FOUND_ROWS for Total Rows with LIMIT

If you're using a LIMIT clause and need the total number of rows without the limit, you can employ the SQL_CALC_FOUND_ROWS and FOUND_ROWS() functions:

<code class="sql">SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value" 
LIMIT 10;

SELECT FOUND_ROWS();</code>
Copy after login

Note: SQL_CALC_FOUND_ROWS is deprecated as of MySQL 8.0.17 and is recommended to be replaced with a separate query to obtain a count.

The above is the detailed content of How to Count the Number of Rows Returned by a MySQL Query?. 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