Home >Backend Development >PHP Tutorial >Why Does MySQLi's `num_rows` Return 1 When Counting Rows?
Exposing the Flaw in MySQLi's Row Counting
In an attempt to determine the count of a table's rows, a code snippet has been implemented:
$result = $db->query("SELECT COUNT(*) FROM `table`;"); $count = $result->num_rows;
However, the count value consistently remains at 1, regardless of the actual number of rows in the table.
Upon further debugging, the issue becomes apparent: the executed query returns a single record with the count value stored in the first column. Therefore, to access the result, the record must be retrieved:
$result = $db->query("SELECT COUNT(*) FROM `table`"); $row = $result->fetch_row(); echo '#: ', $row[0];
This approach guarantees the correct count of rows in the table, even when the query is executed through phpMyAdmin.
The above is the detailed content of Why Does MySQLi's `num_rows` Return 1 When Counting Rows?. For more information, please follow other related articles on the PHP Chinese website!