Home >Database >Mysql Tutorial >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
To execute this command in PHP, you can utilize the mysql_query() function:
$result = mysql_query("SELECT COUNT(1) FROM table_name");
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);
The first element in the resulting array $row contains the total row count:
$total = $row[0];
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);
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!