问题
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