I\'m looking for the best way to check and see if any results were returned in a query. I feel like I write this part of code a lot and sometimes I get errors, and sometimes
Usually I use the ===
(triple equals) and __LINE__
, __CLASS__
to locate the error in my code:
$query=mysql_query('SELECT champ FROM table')
or die("SQL Error line ".__LINE__ ." class ".__CLASS__." : ".mysql_error());
mysql_close();
if(mysql_num_rows($query)===0)
{
PERFORM ACTION;
}
else
{
while($r=mysql_fetch_row($query))
{
PERFORM ACTION;
}
}
$connect = new mysqli('localhost', 'user', 'password', 'db');
$result = $connect->query("select * from ...");
$count=$result->num_rows;
if(empty($count)){
echo"Query returned nothing";
}
else{
echo"query returned results";
}
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.
If you would still like to perform the action if the $result
is invalid:
if(!mysql_num_rows($result))
// Do stuff
This will account for a 0
and the false
that is returned by mysql_num_rows()
on failure.
mysqli_fetch_array()
returns NULL
if there is no row.
In procedural style:
if ( ! $row = mysqli_fetch_array( $result ) ) {
... no result ...
}
else {
... get the first result in $row ...
}
In Object oriented style:
if ( ! $row = $result->fetch_array() ) {
...
}
else {
... get the first result in $row ...
}