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?

3
  • 3
    Missing SELECT in your query try this SELECT Count(*) FROM post_items Commented Feb 19, 2014 at 6:54
  • @MKhalidJunaid didn't work too Commented Feb 19, 2014 at 6:56
  • Does this answer your question? MySQLi count(*) always returns 1 Commented Mar 6, 2020 at 19:47

3 Answers 3

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

3 Comments

then that's not what I want. I need to know the total row in the table. like 50 customers has bought an item.
echoing the count will do that for you, mysqli_num_rows returns no of rows not the data of rows
to get data you will have to fetch the result and then display it, check updated ans
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.

Comments

-3

It should be

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.