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?
We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function. Syntax: mysqli_num_rows( result ); The result is to specify the result set identifier returned by mysqli_query() function.
The mysqli_num_rows() function returns the number of rows in a result set.
Return value: For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
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.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With