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

How to Count Rows in MySQL Tables Using PHP?

Mary-Kate Olsen
Release: 2024-10-21 19:28:29
Original
606 people have browsed it

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

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

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

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!

source:php
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