1

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. I do not know much PHP and specially does not know more about query. Let me know if someone can help me for get out from this. Thanks

Raju Bhatt
  • 385
  • 5
  • 17

3 Answers3

0

Try this:

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

Hope it will work.

Qirel
  • 25,449
  • 7
  • 45
  • 62
Strange
  • 310
  • 5
  • 20
0

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. - How to create a secure mysql prepared statement in php?

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Glad to help, if this has answered your question, please consider marking it as answered - https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work. – Nigel Ren Nov 21 '18 at 07:23
0

You can also use 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();
} 
Qirel
  • 25,449
  • 7
  • 45
  • 62
Krishna
  • 438
  • 5
  • 18