Best way to check if MySQL results returned in PHP?

前端 未结 11 1050
长情又很酷
长情又很酷 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: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.

提交回复
热议问题