How to Retrieve a Single-Row Result from a MySQL Query Using PHP
In PHP, while fetching data from a MySQL database, it is common to retrieve both the value and row of a query result. However, obtaining a single output from a query, such as the result of a COUNT(*) aggregation function, can pose a challenge.
To display the result of a COUNT(*) query, you need to alias the aggregate using the as keyword. Here's how to do it:
$result = mysql_query("SELECT COUNT(*) as total from Students"); $data = mysql_fetch_assoc($result); echo $data['total'];
By aliasing the aggregate as "total" in the query, you can access the value using $data['total']. This will output the count of rows from the Students table.
Note that the example uses the deprecated mysql_* functions. You are recommended to use mysqli_* or PDO functions for modern PHP development.
The above is the detailed content of How to Fetch a Single Value from a MySQL Query in PHP?. For more information, please follow other related articles on the PHP Chinese website!