Best way to check if MySQL results returned in PHP?

前端 未结 11 1046
长情又很酷
长情又很酷 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-29 00:10

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

    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.

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

    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.

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

    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 ...
    }
    
    0 讨论(0)
提交回复
热议问题