Home >Backend Development >PHP Tutorial >How to Fetch a Single Value from a MySQL Query in PHP?

How to Fetch a Single Value from a MySQL Query in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 21:56:11878browse

How to Fetch a Single Value from a MySQL Query in PHP?

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!

Statement:
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