Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi count(*) always returns 1

Tags:

php

mysql

mysqli

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?

like image 398
Lode Avatar asked Aug 31 '10 20:08

Lode


People also ask

How can I count the number of rows in Mysqli using PHP?

We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function. Syntax: mysqli_num_rows( result ); The result is to specify the result set identifier returned by mysqli_query() function.

What does Mysqli_num_rows return?

The mysqli_num_rows() function returns the number of rows in a result set.

What does Mysqli_query return?

Return value: For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.


2 Answers

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]; 
like image 168
VolkerK Avatar answered Sep 21 '22 02:09

VolkerK


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.";
like image 20
ErVeY Avatar answered Sep 19 '22 02:09

ErVeY