Counting Total Rows in a MySQL Table Using PHP
Counting the total number of rows in a MySQL table is a common operation in PHP development. This can be useful for various tasks, such as paginating data or generating summaries. Here's how to do it:
In your PHP script, establish a connection to the MySQL server using mysql_connect() and select the desired database using mysql_select_db().
The most straightforward approach is to use the MySQL command SELECT COUNT(*) FROM table_name. This will return the total number of rows in the specified table. Execute this query using mysql_query().
To fetch the result of the query, use mysql_fetch_array(). The first element of the resulting array will contain the count.
Finally, you can store the count in a variable for further processing or display it using echo.
Here's an example of how the PHP code would look like:
$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"); $row = mysql_fetch_array($result); $total = $row[0]; echo "Total rows: " . $total; mysql_close($con);
The above is the detailed content of How to Count Total Rows in a MySQL Table Using PHP?. For more information, please follow other related articles on the PHP Chinese website!