0
if($sql = $db->query("Count (*) FROM post_items")){
        echo mysqli_num_rows($sql);
}

what's wrong with my code? is this the correct way to echo the total of row in a table?

Dharman
  • 30,962
  • 25
  • 85
  • 135

3 Answers3

3

Your query should be

select count(*) FROM post_items

but echoing

mysqli_num_rows($sql); 

will always give 1 as the ans, because count function returns only one row.

Rather fetch the details and show the count

$row = $sql->fetch_row();
echo $row[0];
Dharman
  • 30,962
  • 25
  • 85
  • 135
Deepika Janiyani
  • 1,487
  • 9
  • 17
2

No it is not; you will always get a return value of 1.

Why? Because you are in essence double-counting. The query executes a COUNT aggregate on the table returning a single row with the counted number. mysqli_num_rows is then counting the number of rows in this result set - the single row - and returns 1.

Try, the following line instead, which should fetch the first (only) column returned of the first (only) row in the result set.

echo $sql->fetch_row()[0]

Note you're also missing a SELECT keyword in your SQL statement.

lc.
  • 113,939
  • 20
  • 158
  • 187
-3

It should be

if($sql = $db->query("select count(*) FROM post_items")){
        echo mysqli_num_rows($sql);
}
Akhil Sidharth
  • 746
  • 1
  • 6
  • 16