Home >Database >Mysql Tutorial >Why Does My MySQLi `COUNT(*)` Query Always Return 1?

Why Does My MySQLi `COUNT(*)` Query Always Return 1?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 01:04:10526browse

Why Does My MySQLi `COUNT(*)` Query Always Return 1?

MySQLi Count(*) Consistently Returns 1: An Explanation

When encountering the issue where MySQLi's count(*) always returns 1, it is crucial to understand that the query does not directly return the count as a value. Instead, it returns a result set containing a single record with the count as its data.

To access the actual count, you need to fetch this record from the result set. The following code snippet demonstrates how to do this:

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

By fetching the first row of the result set, you retrieve an array where the first element contains the count value. This provides the correct result, which differs from the result obtained in phpMyAdmin, where the count is displayed directly in the query results.

Remember, MySQLi's num_rows property provides the number of affected rows in insert, update, or delete operations. It is not suitable for retrieving count values in select queries.

The above is the detailed content of Why Does My MySQLi `COUNT(*)` Query Always Return 1?. 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