Home » Php » php – MySQLi count(*) always returns 1

php – MySQLi count(*) always returns 1

Posted by: admin February 25, 2020 Leave a comment


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?

How to&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];


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


It’s very simple:

$query = "select count(*)as count from users";
$result = $connection->query($query);
$count = $result->fetch_assoc()["count"];
echo $count;


This worked well for me.

// Veh Pro Count
$query_tvp = "SELECT count(*) as total from submit";
if ($result_tvp = $mysqli->query("$query_tvp")) {
    /* determine number of rows result set */
    $total_tvp = $result_tvp->fetch_row();
    $total_tvp = $total_tvp['0'];
    /* close result set */

echo "Total: $total_tvp";


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…


For me this works, this is when you want to count a
repeated elements inside a register.

For example: number of people who mark ‘yes’ in a form.

table: users

register: vote

element of register: yes / no

$sql_user = "SELECT COUNT(*) FROM users WHERE vote = 'yes'";    
$result1 = $mysqli->query($sql_user);    
$row1 = $result1->fetch_row();    
$n_yes = $row1['0'];