Home > Backend Development > PHP Tutorial > How to Efficiently Retrieve the Row Count of a MySQL Table Using PHP?

How to Efficiently Retrieve the Row Count of a MySQL Table Using PHP?

Mary-Kate Olsen
Release: 2024-12-06 00:48:10
Original
897 people have browsed it

How to Efficiently Retrieve the Row Count of a MySQL Table Using PHP?

How to Retrieve Row Count in MySQL Table Using PHP Procedurally

You seek to determine the total number of rows in a MySQL table and store it in a variable, $count. Your initial attempt yielded the word "Array" instead.

The solution involves utilizing mysqli_fetch_assoc($result) to retrieve the count value. Here are three ways to do so:

  1. Using Column Alias:
$sql = "SELECT COUNT(*) AS cnt FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_assoc($result)['cnt'];
Copy after login
  1. Using Numerical Array:
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_row($result)[0];
Copy after login
  1. PHP 8.1 and Above:
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_column($result);
Copy after login

Additionally, it's recommended to learn OOP (Object-Oriented Programming) for cleaner and more readable code. The OOP version of your code:

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

For queries with variables, prepared statements can be employed:

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

The above is the detailed content of How to Efficiently Retrieve the Row Count of 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