Home > Database > Mysql Tutorial > Why Does My MySQLi `COUNT(*)` Always Return 1?

Why Does My MySQLi `COUNT(*)` Always Return 1?

Barbara Streisand
Release: 2024-12-02 19:28:12
Original
577 people have browsed it

Why Does My MySQLi `COUNT(*)` Always Return 1?

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];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template