"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-12-21
Browse:626

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'];
  1. Using Numerical Array:
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_row($result)[0];
  1. PHP 8.1 and Above:
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_column($result);

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];

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];
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3