71

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 I don't.

For example, I run this query to check if a username exists before inserting a new one into the database.

$result = mysql_query("SELECT * FROM ...");

Then I want to check and see if any results were returned. Here is one way I do it:

if (!$result) { PERFORM ACTION }

If the first way doesn't work, then sometimes this will:

if (mysql_num_rows($result)==0) { PERFORM ACTION }

Then I even saw that I could do it this way the other day:

list($total) = mysql_fetch_row($result);
if ($total==0) { PERFORM ACTION }

What is the best way to do this?

timroman
  • 1,304
  • 1
  • 10
  • 17
  • For this example, let's assume that the query is not producing an error. – timroman Nov 26 '10 at 15:55
  • If there is no error in the query, the first test is meaningless then. The second is the best way if its a "SELECT \*" the last is only useful if you have a SELECT COUNT(\*) or other aggregated function. But please for sanity sakes, use PDO :-) – Rahly Nov 26 '10 at 16:50

11 Answers11

152
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

benhowdle89
  • 34,076
  • 63
  • 192
  • 314
  • 5
    @benhowdle89 - If sql fail, $result is not a valid mysql result resource, what can mysql_num_rows do ? – ajreal Nov 26 '10 at 15:46
  • 3
    true, but it was hardly worth a vote down!? It still a valid method to check the O/P question: I'm looking for the best way to check and see if any results were returned in a query. – benhowdle89 Nov 26 '10 at 15:48
  • 6
    Racertim asked how to check the number of rows - and not if the SQL fails, so this is a legitime answer. Vote up for this. – acme Nov 26 '10 at 15:50
  • 6
    mysql_num_rows will return false if $result is invalid http://php.net/manual/en/function.mysql-num-rows.php – slim Nov 26 '10 at 15:50
  • is not valid method to check, restore back – ajreal Nov 26 '10 at 15:50
  • @Shady - anything except the last used mysql_result will also return false – ajreal Nov 26 '10 at 15:52
  • Testing with "empty()" could be an option if it's not necessary to know if the statement fails or if the query returned zero rows. – acme Nov 29 '10 at 13:09
  • Just in case if some one was looking for PDO command it would be rowcount for pdo .http://php.net/manual/en/pdostatement.rowcount.php – pal4life Mar 15 '12 at 18:52
  • this should be if (mysql_num_rows($result)>0) not equal – Tom May 19 '12 at 13:23
  • @Tom, if you read OP's question carefully, you will see that he performs action when there are no results, so it is correct as shown. – ToolmakerSteve Sep 05 '15 at 10:27
  • 1
    **Update :** Use `mysqli_num_rows($result) == 0` as mysql_num_rows($result) doesn't works with php version > 7 _(that I checked)_ – Mohammad Mahroz Apr 24 '17 at 15:47
  • Thanks so much for sharing @benhowdle89 you are god :) – Tomas M Jan 20 '21 at 21:16
14

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.

Shoe
  • 70,092
  • 30
  • 150
  • 251
  • 2
    [Upvoted for content, but wanted to mention this.] Minor style nit: I hate seeing "=" inside an if. Too similar to "==". Easier to read if do the assignment *before* the `if`. (I spend a lot of time in my career debugging other people's code...) – ToolmakerSteve Jan 09 '17 at 20:11
7

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
}
  • No, don't use `empty`. Lots of other stackoverflow posts talk about doing so causing mistakes, when a value could be `0` or `'0'`, *in php these are equal to false*. You need to test that $result is (not) specifically, identically, `false`. IMPORTANT: also wrong would be `if (result != false)`, for the same reason. Correct code is `if ($result !== false)`. – ToolmakerSteve Jan 09 '17 at 20:15
2

What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.

$result = mysqli_query($dbs, $sql);

if(gettype($result)=='boolean'){ // test for boolean
    if($result){  // returned TRUE, e.g. in case of a DELETE sql  
        echo "SQL succeeded"; 
    } else { // returned FALSE
        echo "Error: " . mysqli_error($dbs);
    } 
} else { // must be a resource
    if(mysqli_num_rows($result)){

       // process the data    

    }
    mysqli_free_result($result);  
 }
G. Moore
  • 67
  • 1
  • 3
    Upvoted as a valid, clear, option. However in practice, the same result is achieved by simpler code: `if ($result === false)`. NOTE: this must be `===` not `==`. That guarantees that you are testing only for "boolean false". The opposite test would be `if ($result !== false)`. – ToolmakerSteve Jan 09 '17 at 20:20
2
$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";
} 
Toki
  • 177
  • 1
  • 7
1

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 ...
}
xavier bs
  • 1,181
  • 1
  • 10
  • 7
1

Of all the options above I would use

if (mysql_num_rows($result)==0) { PERFORM ACTION }

checking against the result like below

if (!$result) { PERFORM ACTION }

This will be true if a mysql_error occurs so effectively if an error occurred you could then enter a duplicate user-name...

martynthewolf
  • 1,658
  • 11
  • 22
0

Use the one with mysql_fetch_row because "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. "

cristian
  • 8,300
  • 3
  • 35
  • 44
  • 1
    No way, mysql_fetch_row will fetch the results. He is asking for knowing if a result is returned or not, considering a SELECT. – Shoe Nov 26 '10 at 15:46
-1
$result = $mysqli->query($query);
if($result){
    perform action
}

this is how i do it, you could also throw an else there with a die...

-1

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.

D. Mariano
  • 29
  • 5
-1

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;
    }
}
Community
  • 1
  • 1
Amirouche Douda
  • 1,506
  • 1
  • 20
  • 29