php - How to get number of returned rows from a database

621

After I perform a database query, and some rows are echoed, it seems that I can't get the number of rows which are shown, after the query. Tried to use mysql_num_rows() but my $result is like this:

$result = $conn->query($sql) or die();

so I think that the problem is that I've used the built-in MySQLi() class, and for some reason mysql_num_rows() is not working in accordance with this $result. How can I get it to work with the current $result I'm using, or is there any other way to return the number of rows using the MySQLi() class to create the $result??

78

Answer

Solution:

mysql and mysqli are NOT interchangeable. They're two completely different modules, maintain their own separate connections, and are results/handles from one are NOT useable in the other. They may both use the same underlying mysql libraries and talk to the same database, but they're utterly independent of each other.

If you're using MySQLi, then stick with MySQLi functions, which for your problem would be to use http://php.net/manual/en/mysqli-stmt.num-rows.php

593

Answer

Solution:

Note1: If you only need the number of rows in your table, it is better to do the folowing:

$result = $conn->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

Note 2: Don't mix up mysqli_field_count and mysqli_stmt_num_rows. For example :

id firstname
1  foo
2  bar
3  baz
  • field_count is 2
  • num_rows is 3

People are also looking for solutions to the problem: javascript - Valid JSON to display data in angularJs

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.