简体   繁体   English

php mysqli 检查 mysqli 查询是否返回 false

[英]php mysqli check if mysqli query returns false

How can I check mysqli query if it returns boolean(false) or the result?如何检查 mysqli 查询是否返回 boolean(false) 或结果? If I try getting the num_rows I get php error because I'm trying to access a non object as object.如果我尝试获取 num_rows 我得到 php 错误,因为我试图访问一个非对象作为对象。 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);
?>

You need to use === operator which also checks arguments type: 您需要使用===运算符,该运算符还会检查参数类型:

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

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

To know if a variable is set to false, you can use 要知道变量是否设置为false,可以使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM