Home > Database > Mysql Tutorial > How to Retrieve Aggregate Values (e.g., COUNT(*)) from MySQL Queries in PHP?

How to Retrieve Aggregate Values (e.g., COUNT(*)) from MySQL Queries in PHP?

Barbara Streisand
Release: 2024-12-30 02:54:13
Original
955 people have browsed it

How to Retrieve Aggregate Values (e.g., COUNT(*)) from MySQL Queries in PHP?

Retrieving Aggregate Values from MySQL Queries in PHP

When working with aggregate functions like COUNT(*), it's crucial to understand how to extract the result as a single value.

In PHP, executing a query like SELECT COUNT(*) FROM Students; returns a resource handle representing the result set. To access the count, we need to alias the aggregated expression using the AS keyword.

$result = mysql_query("SELECT COUNT(*) AS total FROM Students;");
Copy after login

With the alias set, we can fetch the result using mysql_fetch_assoc() or mysql_fetch_row(). However, mysql_fetch_assoc() is preferred since it returns an associative array where the alias is used as the key.

$data = mysql_fetch_assoc($result);
echo $data['total'];
Copy after login

This code assigns the total count to the $data array and prints the count using the alias as the key.

Note: Remember to use mysqli functions (e.g., mysqli_query(), mysqli_fetch_assoc()) instead of mysql functions for better security and compatibility.

The above is the detailed content of How to Retrieve Aggregate Values (e.g., COUNT(*)) from MySQL Queries 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