Home >Backend Development >PHP Tutorial >Why Does MySQLi's `num_rows` Return 1 When Counting Rows?

Why Does MySQLi's `num_rows` Return 1 When Counting Rows?

DDD
DDDOriginal
2024-11-08 09:55:02325browse

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!

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