46

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?

Lode
  • 2,160
  • 1
  • 20
  • 25

4 Answers4

107

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
  • 95,432
  • 20
  • 163
  • 226
  • Thanks! So num_rows only should be used for `SELECT *` instead of `SELECT COUNT`? – Lode Sep 01 '10 at 06:34
  • 4
    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 Sep 01 '10 at 09:15
12

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.";
Dharman
  • 30,962
  • 25
  • 85
  • 135
ErVeY
  • 1,524
  • 4
  • 16
  • 26
3

I find this way more readable:

$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";

Not that I have anything against arrays...

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mike Causer
  • 8,196
  • 2
  • 43
  • 63
0

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

Stephane Paquet
  • 2,315
  • 27
  • 31
  • 4
    Incorrect. mysqli_result::$num_rows returns the row count of a result set. mysqli::$affected_rows returns the number of rows affected by a query. –  Aug 08 '13 at 06:16