Home > Database > Mysql Tutorial > How to Efficiently Count Total Rows in a MySQL Table Using PHP?

How to Efficiently Count Total Rows in a MySQL Table Using PHP?

DDD
Release: 2024-11-27 02:02:10
Original
627 people have browsed it

How to Efficiently Count Total Rows in a MySQL Table Using PHP?

Counting Total Table Rows in PHP Using MySQL

In PHP, obtaining the total count of rows in a MySQL table can be achieved effectively. This article will guide you through the optimal approach and provide a practical PHP code example.

The recommended MySQL command for counting the total number of rows in a table without any conditions is:

SELECT COUNT(1) FROM table_name
Copy after login

To execute this command in PHP, you can utilize the mysql_query() function:

$result = mysql_query("SELECT COUNT(1) FROM table_name");
Copy after login

The resulting variable $result holds the query's result set. To retrieve the actual row count, use the mysql_fetch_array() function:

$row = mysql_fetch_array($result);
Copy after login

The first element in the resulting array $row contains the total row count:

$total = $row[0];
Copy after login

Here's an enhanced version of your PHP code incorporating these steps:

$con = mysql_connect("server.com","user","pswd");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("db", $con);

$result = mysql_query("SELECT COUNT(1) FROM table_name");
$row = mysql_fetch_array($result);

$total = $row[0];
echo "Total rows: " . $total;

mysql_close($con);
Copy after login

This PHP script will connect to the database, execute the query, retrieve the row count, and display it.

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

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