Home > Article > Backend Development > Why Does MySQLi count(*) Always Return 1?
Troubleshooting MySQLi Count(*) Consistently Reporting "1"
When attempting to count the number of rows in a MySQL table using MySQLi, you may encounter an issue where count(*) always returns 1, despite the expected count. This can be a perplexing problem, as the query seems syntactically correct.
To resolve this issue, it's important to understand that count(*) returns a result in a single row, which must be fetched using fetch_row(). The following code demonstrates the correct approach:
$result = $db->query("SELECT COUNT(*) FROM `table`"); $row = $result->fetch_row(); echo "Count: ", $row[0];
In this code, the query is executed as usual, and then the fetch_row() method is employed to retrieve the result row. The value of count(*) is then obtained from the row at index 0. This approach ensures that you obtain the accurate count of rows in the table.
The above is the detailed content of Why Does MySQLi count(*) Always Return 1?. For more information, please follow other related articles on the PHP Chinese website!