SELECT COUNT(*) AS count - How to use this count
Solution 1:
It's not recommended to use reserved words for names in SQL. So I call the count result cnt instead. As your function is scalar, i.e. you expect only one value back, you can use:
$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt;
Solution 2:
Select queries always return a resultset.
To take the count, use fetch_row()
$result = $db->query("SELECT COUNT(*) FROM `cars`");
$cars= $result->fetch_row();
echo '#: ', $cars[0];// or use $c= $cars[0];
Solution 3:
You need to get first row of your result and see the 'count' column value:
$cars = $mysqli->query("SELECT COUNT(*) as count FROM cars");
$firstrow = $cars->fetch_assoc();
if ($firstrow['count'] > 0)
{
// ...
}
Solution 4:
If result is an object then:
$cars = $mysqli->query("SELECT count(*) as count FROM cars");
$carRows = $cars->result();
echo $carRows[0]->count;
If you return array then:
$cars = $mysqli->query("SELECT count(*) as count FROM cars");
$carRows = $cars->result_array();
echo $carRows[0]['count'];