Best way to check if MySQL results returned in PHP?
if (mysql_num_rows($result)==0) { PERFORM ACTION }
For PHP 5 and 7 and above use mysqli:
if (mysqli_num_rows($result)==0) { PERFORM ACTION }
This gets my vote.
OP assuming query is not returning any error, so this should be one of the way
One way to do it is to check what mysql_num_rows
returns. A minimal complete example would be the following:
if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
// there are results in $result
} else {
// no results
}
But it's recommended that you check the return value of mysql_query
and handle it properly in the case it's false
(which would be caused by an error); probably by also calling mysql_error
and logging the error somewhere.
Whenever we do queries to get some data, it is returned as an object. Then most of us convert it to array for looping through the rows easily. In php "empty()" function is used to check if an array is empty i.e. if it has no data in it. So we can check if returned array representation of query isn't empty by doing like this
if(!empty($result)){
//DO STUFF
}