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

How to Efficiently Count Rows in MySQL Tables Using PHP?

Mary-Kate Olsen
Release: 2024-12-03 02:21:09
Original
760 people have browsed it

How to Efficiently Count Rows in MySQL Tables Using PHP?

How to Retrieve Row Counts from MySQL Tables in PHP

Your PHP code, which aims to count rows in a MySQL table and store the result in $count, encountered difficulties. In this article, we will explore how to effectively achieve this using PHP's procedural style.

Procedural Row Counting

To obtain the row count, consider the following modifications to your code:

$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_assoc($result)['COUNT(*)'];
echo $count;
Copy after login

In this version, we access the result of COUNT(*) directly by selecting the appropriate column from the associative array returned by mysqli_fetch_assoc().

Alternative Methods

Apart from the above method, here are some additional options:

  • Using Column Aliasing:
$sql = "SELECT COUNT(*) AS cnt FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_assoc($result)['cnt'];
echo $count;
Copy after login
  • Using Numerical Arrays:
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_row($result)[0];
echo $count;
Copy after login
  • PHP 8.1 and Later:
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_column($result);
echo $count;
Copy after login

Avoid Using mysqli_num_rows

Contrary to popular advice, mysqli_num_rows should not be used for row counting. It retrieves all matching records, which can be inefficient and resource-intensive.

Prepared Statements for Parameterized Queries

If your query involves dynamic variables, consider using prepared statements:

$sql = "SELECT COUNT(*) FROM news WHERE category=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('s', $category);
$stmt->execute();
$count = $stmt->get_result()->fetch_row()[0];
echo $count;
Copy after login

The above is the detailed content of How to Efficiently Count Rows in MySQL Tables Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

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