How to Count Rows in MySQL with PHP Using SELECT COUNT(*)

Barbara Streisand
Release: 2024-10-21 19:27:29
Original
988 people have browsed it

How to Count Rows in MySQL with PHP Using SELECT COUNT(*)

Counting Rows in MySQL with PHP

The SELECT COUNT(*) function is commonly used to count rows in MySQL. To use it through PHP, follow these steps:

  1. Establish a MySQL Connection:
    Start by establishing a connection to your MySQL database using mysql_connect(). Ensure that you provide the correct server, username, and password.
  2. Select the Database:
    Select the database you want to count rows from using mysql_select_db().
  3. Count Rows Using SELECT COUNT(*):
    Execute a query using mysql_query(). The query should include the SELECT COUNT(*) FROM table_name statement. This will return a result resource.
  4. Fetch the Result:
    Use mysql_fetch_array() to retrieve the result. The first element of the returned array represents the total number of rows.
  5. Close the Connection:
    Finally, close the MySQL connection using mysql_close().

PHP Example:

<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

This code establishes a connection, selects the database, executes the COUNT(*) query, fetches the result, stores the total in the $total variable, and finally prints it out.

The above is the detailed content of How to Count Rows in MySQL with PHP Using SELECT COUNT(*). 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!