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;");
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'];
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!