Home > Backend Development > PHP Tutorial > How to Get a Single COUNT(*) Result from a MySQL Query in PHP?

How to Get a Single COUNT(*) Result from a MySQL Query in PHP?

Linda Hamilton
Release: 2024-11-30 03:24:14
Original
674 people have browsed it

How to Get a Single COUNT(*) Result from a MySQL Query in PHP?

Getting Single Output from MySQL COUNT(*) Query in PHP

In PHP, MySQL queries that retrieve a single value, such as those using the COUNT() aggregate function, can be challenging to work with. This article addresses the common issue of retrieving and displaying the result of a COUNT() query.

The provided error message suggests that the issue lies in retrieving the single output value from the query. To resolve this, it is necessary to alias the aggregate using the AS keyword. This creates a temporary column that can be referred to when fetching the result.

Here's a corrected example using the MySQLImproved extension:

$result = mysqli_query($connection, "SELECT COUNT(*) AS total FROM Students");
$data = mysqli_fetch_assoc($result);
echo $data['total'];
Copy after login

In this example, the aggregate function is aliased as total. When using mysqli_fetch_assoc(), you can then access the result using the alias, $data['total']. This should display the count of rows in the Students table.

By aliasing the aggregate and using the correct retrieval function, you can successfully obtain and display the single output of a COUNT(*) query in PHP.

The above is the detailed content of How to Get a Single COUNT(*) Result from a MySQL Query in 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