MySQLi count(*) always returns 1

Lode picture Lode · Aug 31, 2010 · Viewed 99k times · Source

I'm trying to count the number of rows in a table and thought that this was the correct way to do that:

$result = $db->query("SELECT COUNT(*) FROM `table`;");
$count = $result->num_rows;

But counts always returns (int)1. If I use the same query in phpMyAdmin I get the right result. It sits in a table so I tried testing $count[0] as well, but that returns NULL.

What is the right way to do this?

Answer

VolkerK picture VolkerK · Aug 31, 2010

You have to fetch that one record, it will contain the result of Count()

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];