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

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

Mary-Kate Olsen
Release: 2024-11-24 04:43:10
Original
369 people have browsed it

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

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);
Copy after login

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template