skip to Main Content

This is my PHP code snippet:

$conn = mysqli_connect($servername, $dbusername, $dbupassword, $dbname);
$sql = "SELECT COUNT(*) FROM `users`;";
$count = $conn->query($sql);
echo $count->num_rows;

It always echos 1 even though I have 5 users in my table (see image below). enter image description here

I also tried using COUNT(1) but it also returned 1. But when I change the statement to SELECT * FROM `users`; it returns 5.

If I do a var_dump($count) (same code as above but I don’t use the num_rows), I get the information below:

object(mysqli_result)#2 (5) {
  ["current_field"]=> int(0)
  ["field_count"]=> int(1)
  ["lengths"]=> NULL
  ["num_rows"]=> int(1)
  ["type"]=> int(0)
}

I am running phpMyAdmin, Version information: 5.0.2, with database version: 10.4.14-MariaDB, and PHP 7.4.10

2

Answers


  1. $conn = mysqli_connect($servername, $dbusername, $dbupassword, $dbname);
    $sql = "SELECT COUNT(*) FROM `users`;";
    $result = $conn->query($sql);
    $row = $result->fetch_row();
    echo "row count = " . $row['0'];
    var_dump($row);
    
    Login or Signup to reply.
  2. if you want to count the row of table, just run query "SELECT COUNT() FROM users".
    Its return one row that contain total table row. Dont use num_rows method, because "SELECT COUNT(
    ) FROM users" query, just return one row

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search