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?

0

4 Answers 4

108

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]; 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So num_rows only should be used for SELECT * instead of SELECT COUNT?
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(*).
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."; 

1 Comment

Curious what do you mean by multiple case result? A select with multiple counts using case statements?
4

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...

Comments

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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.