Best way to check if MySQL results returned in PHP?

前端 未结 11 1045
长情又很酷
长情又很酷 2020-11-28 23:21

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

相关标签:
11条回答
  • 2020-11-28 23:58
    $result = $mysqli->query($query);
    if($result){
        perform action
    }
    

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

    0 讨论(0)
  • 2020-11-28 23:59

    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
    }
    
    0 讨论(0)
  • 2020-11-28 23:59

    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. "

    0 讨论(0)
  • 2020-11-29 00:01
    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

    0 讨论(0)
  • 2020-11-29 00:01

    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);  
     }
    
    0 讨论(0)
  • 2020-11-29 00:06

    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...

    0 讨论(0)
提交回复
热议问题