Incorrect MySQLi Count(*) Result: Always Returns 1
In an attempt to retrieve the number of rows in a table, you encountered an issue where the $result->num_rows count consistently returned 1. Despite using the correct query in phpMyAdmin and obtaining the expected result, the PHP method behaved unexpectedly.
To correct this behavior, you need to understand that COUNT(*) is an aggregate function that returns a single value. To retrieve this value, you need to fetch the result from the query using $result->fetch_row(). The first element in the resulting array ($row[0]) will contain the count.
Here is the corrected code:
$result = $db->query("SELECT COUNT(*) FROM `table`"); $row = $result->fetch_row(); echo '#: ', $row[0];
By incorporating this change, you will now correctly obtain the count of rows in your table.
The above is the detailed content of Why Does My MySQLi `COUNT(*)` Always Return 1?. For more information, please follow other related articles on the PHP Chinese website!