Home >Backend Development >PHP Tutorial >How to Count Rows in MySQL Tables Using PHP?
Counting Rows in MySQL Tables Using PHP
When working with large datasets, it's often necessary to count the total number of rows in a table. MySQL provides a simple way to perform this count using the COUNT() function.
MySQL Command
To count the total number of rows in a table without any conditions, simply use the following MySQL command:
SELECT COUNT(*) FROM table_name;
PHP Implementation
In PHP, you can use the mysql_query() function to execute the MySQL query and store the result in a variable. Then, you can use the mysql_fetch_array() function to retrieve the first row of the result, which contains the count value.
<code class="php">$result = mysql_query("SELECT COUNT(*) FROM table_name"); $row = mysql_fetch_array($result); $total = $row[0]; echo "Total rows: " . $total;</code>
Example Usage
Consider the following PHP script:
<code class="php"><?php $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(*) FROM table_name"); $row = mysql_fetch_array($result); $total = $row[0]; echo "Total rows: " . $total; mysql_close($con); ?></code>
When this script is executed, it will connect to the specified MySQL database, execute the SELECT COUNT(*) FROM table_name query, and print the total number of rows in the table_name table.
The above is the detailed content of How to Count Rows in MySQL Tables Using PHP?. For more information, please follow other related articles on the PHP Chinese website!