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

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

Patricia Arquette
Release: 2024-11-29 03:30:18
Original
575 people have browsed it

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

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

In PHP, using MySQL extension to interact with MySQL database, it can be challenging to retrieve the single output of a COUNT(*) query. Here's an exploration of the issue and a solution to obtain the expected result.

To fetch the single output of a query, it's necessary to alias the aggregate using the as keyword. For example, consider the following query:

SELECT COUNT(*) FROM Students;
Copy after login

If you try to retrieve the result using mysql_fetch_assoc() or mysql_fetch_row(), you'll notice that you won't get the expected value. This is because the COUNT(*) query returns a single column without a name.

To resolve this issue, alias the aggregate using the as keyword like this:

SELECT COUNT(*) as total FROM Students;
Copy after login

This will create a new column named total that contains the count value. Now, you can use mysql_fetch_assoc() to retrieve the result and access the total column.

$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];
Copy after login

By using this approach, you can successfully retrieve and display the single output from your MySQL COUNT(*) query in PHP.

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