Home  >  Article  >  Backend Development  >  Why Does MySQLi count(*) Always Return 1?

Why Does MySQLi count(*) Always Return 1?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 13:52:02789browse

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!

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