简体   繁体   English

没有任何结果时,MySQLi查询给出错误

[英]MySQLi query giving error when there no any result

I am trying to find and echo one result from my database. 我正在尝试从数据库中查找并回显一个结果。 I am using it like below 我正在如下使用

<?php
error_reporting(E_ALL);
include_once("includes/connection.php");
$input = "OUT";
$answer = $mysqli->query("SELECT answer FROM faq WHERE question LIKE '%".$input."%' LIMIT 1")->fetch_object()->answer; 
echo $answer;
?>

Its working fine when there some result but giving error like below when there no any result 当有结果时,它工作正常,但无结果时,出现如下所示的错误

Notice: Trying to get property 'answer' of non-object in C:\xampp\htdocs\new\test.php on line 5

I want handle this error using if else. 我想使用if来处理此错误。 I do not know much PHP and specially does not know more about query. 我对PHP不太了解,特别是对查询不了解。 Let me know if someone can help me for get out from this. 让我知道是否有人可以帮助我摆脱困境。 Thanks 谢谢

Try this: 尝试这个:

if ($answer) {
    echo $answer;
} else {
    die('No Answer Found');
}

Hope it will work. 希望它能工作。

It's caused by the overuse of method chaining, why do you need to put every call in one long line? 这是由于方法链接的使用过多而引起的,为什么您需要将每个调用放在一行中?

You should check if an object is retrieved first... 您应该检查是否首先检索到对象...

$query = $mysqli->query("SELECT answer FROM faq WHERE question LIKE '%".$input."%' LIMIT 1");
if ( $query && ($row = $query->fetch_object()) ) {
    $answer = $row->answer; 
    echo $answer;
}

You should also look into prepared statements as this may lead to SQL injection and other problems. 您还应该研究准备好的语句,因为这可能导致SQL注入和其他问题。 - How to create a secure mysql prepared statement in php? - 如何在php中创建安全的mysql准备语句?

You can also use try{} catch {} 您也可以使用try{} catch {}

try {
    $answer = $mysqli->query("SELECT answer FROM faq WHERE question LIKE '%".$input."%' LIMIT 1")->fetch_object()->answer; 
}
catch (Exception $e) {
    $errormsg = $e->getMessage();
} 

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

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