Home >Database >Mysql Tutorial >How to Efficiently Count MySQL Table Rows Using PHP?

How to Efficiently Count MySQL Table Rows Using PHP?

DDD
DDDOriginal
2024-11-25 21:31:12258browse

How to Efficiently Count MySQL Table Rows Using PHP?

Counting Table Rows Using MySQL and PHP

This discussion explores the optimal MySQL command for determining the total number of rows in a table without any specified conditions.

Consider a PHP script that interacts with a MySQL database:

$con = mysql_connect("server.com", "user", "pswd");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("db", $con);

$result = mysql_query("some command");
$row = mysql_fetch_array($result);

mysql_close($con);

For the purpose of counting table rows, a suitable MySQL command is "select count(1) FROM table". By utilizing this command in PHP, it becomes possible to perform the count:

$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(1) FROM table");
$row = mysql_fetch_array($result);

$total = $row[0];
echo "Total rows: " . $total;

mysql_close($con);

This updated script executes the specified command and retrieves the total count as $total, which is then displayed on the screen.

The above is the detailed content of How to Efficiently Count MySQL Table Rows 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