tags:

views:

108

answers:

2

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?

+8  A: 

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];
VolkerK
Thanks!So num_rows only should be used for `SELECT *` instead of `SELECT COUNT`?
Lode
More or les, yes. `num_rows` can tell you how many result records _have been transferred_ to the client. If that's the number you want to know num_rows is what you should use. If you want to know how many records there are in the database (without transferring the data to the client) use Count(*).
VolkerK
+2  A: 

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

$result->close();
ErVeY