Home  >  Article  >  Backend Development  >  How to Count Rows in MySQL Tables Using PHP?

How to Count Rows in MySQL Tables Using PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 19:28:29480browse

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!

Statement:
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