php mysqli check if mysqli query returns false

若如初见. 提交于 2019-12-30 12:15:45

问题


How can I check mysqli query if it returns boolean(false) or the result? If I try getting the num_rows I get php error because I'm trying to access a non object as object. But I need to check this because if its false I have to set a variable and if its not than get the result of the query.

my query looks like this:

<?php
$q = "SELECT `id` FROM `table` ORDER BY `id` DESC LIMIT 0, 1";
$res = mysqli->query($q);
?>

回答1:


You need to use === operator which also checks arguments type:

$q = "select ,....";
$res = mysqli->query( $q );

if( $res !== false ) { 
   // query ok
} else {
   // query failed
}



回答2:


To know if a variable is set to false, you can use

if($res === false){//strictly false, no 0 or ''
   //do something
}

In this case you can just say you want to display the error in order to correct it :

$res = mysqli->query($q) or exit mysqli_error();



回答3:


if (!$mysqli->query("SET a=1")) {
    printf("Errormessage: %s\n", $mysqli->error);
}


来源:https://stackoverflow.com/questions/13690195/php-mysqli-check-if-mysqli-query-returns-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!