Home  >  Article  >  Backend Development  >  How to Get the Total Row Count in MySQL Using PHP?

How to Get the Total Row Count in MySQL Using PHP?

DDD
DDDOriginal
2024-10-21 19:30:29522browse

How to Get the Total Row Count in MySQL Using PHP?

Obtaining the Total Row Count in MySQL Using PHP

When working with a database, it's often necessary to retrieve the total number of rows in a specific table. In MySQL, there are various methods to accomplish this task effectively. This article focuses on the most optimized approach using PHP to determine the total row count without applying any conditions to the result.

MySQL Command

The SQL command to count the total rows in a table is:

SELECT COUNT(1) FROM table_name;

This command returns a single row containing a single column that represents the total count of rows in the specified table.

PHP Function

To execute the MySQL query and retrieve the count using PHP, the mysql_query() function can be utilized:

<code class="php">$result = mysql_query("SELECT COUNT(1) FROM table_name");</code>

The mysql_query() function returns a result resource on success. This resource can be used to fetch the result row and extract the total count.

Fetching the Count

To fetch the total count from the result, the mysql_fetch_array() function is used:

<code class="php">$row = mysql_fetch_array($result);</code>

The mysql_fetch_array() function returns an array containing all the values in the first row of the result set. The total count can be accessed by indexing the array at position 0:

<code class="php">$total = $row[0];</code>

Sample PHP Code

The following PHP code can be used to connect to MySQL, execute the query, retrieve the total count, and display it:

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

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

mysql_close($con);
?></code>

This code establishes a connection to the MySQL database, executes the count query, and displays the total number of rows in the specified table.

The above is the detailed content of How to Get the Total Row Count in MySQL 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