Home >Database >Mysql Tutorial >How Can I Efficiently Retrieve the Row Count from a MySQL Table Using PHP?
In MySQL, you often need to count the total number of rows in a table for various purposes, such as pagination or reports. PHP provides a convenient method to accomplish this task.
The most efficient MySQL command to count rows in a table is:
SELECT COUNT(1) FROM table_name
This command calculates the total number of rows in the specified table, regardless of any filters or conditions.
To execute the MySQL command in PHP and retrieve the row count, follow these steps:
// Connect to the MySQL database $con = mysql_connect("server.com", "user", "password"); // Select the database mysql_select_db("database_name", $con); // Execute the MySQL query to count rows $result = mysql_query("SELECT COUNT(1) FROM table_name"); // Fetch the first row of the result set $row = mysql_fetch_array($result); // Get the row count from the first row $total_rows = $row[0]; mysql_close($con); // Display the row count echo "Total rows in 'table_name': " . $total_rows;
This code will connect to the MySQL database, execute the query to count the rows, and then display the total row count.
The above is the detailed content of How Can I Efficiently Retrieve the Row Count from a MySQL Table Using PHP?. For more information, please follow other related articles on the PHP Chinese website!