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

How to Efficiently Count Rows in a MySQL Table Using PHP?

Susan Sarandon
Release: 2024-12-04 11:40:11
Original
283 people have browsed it

How to Efficiently Count Rows in a MySQL Table Using PHP?

How to Count Rows in a MySQL Table Using PHP

To obtain the total count of rows in a MySQL table, PHP provides several methods. Let's delve into the most common approaches.

Using Associative Arrays

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

Using Column Alias

$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 Simplification

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

It's crucial to avoid using mysqli_num_rows, as it fetches all matching records, which can be inefficient. Instead, delegate the counting task to MySQL and retrieve the count as shown above.

Object-Oriented Approach

$sql = "SELECT COUNT(*) FROM news";
$count = $con->query($sql)->fetch_row()[0];
echo $count;
Copy after login

With prepared statements, you can count rows with dynamic queries.

$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

By following these methods, you can efficiently obtain row counts in MySQL tables using PHP.

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