user3506 user3506 - 2 months ago 24
SQL Question

PHP Notice: Trying to get property of non-object (JSON)

I have an issue that made me scratch my head for a whole day...
I'm trying to retrieve my JSON objects but it can't retrieve the data.

I'm making a GET request.
If 'id' is empty it should retrieve ALL my notes in the arraylist of my DB (PHPMyAdmin). Any ideas?

The error I get is this:

PHP VERSION: 5.6.21 Connected Successfully
<br />
<b>Notice</b>: Trying to get property of non-object in
<b>C:\xampp\htdocs\notes.php</b> on line
<b>165</b>
<br />
{
"header": {
"msg": "You have an error in your SQL syntax; check the manual that corresponds
to your MariaDB server version for the right syntax to use near ''notes' WHERE id=6'
at line 1",
"code": 400
},
"body": []
}


This is the code


else if ($method === 'GET')
{
$sql = "";

if(empty($_REQUEST['id']))
{
// GET All Notes
$sql = "SELECT * FROM 'notes' ORDER BY created_date DESC";
}
else
{
//Get one Note
$id = $_REQUEST['id'];
$sql = "SELECT * FROM 'notes' WHERE id=$id";
}

$result = $conn->query($sql);

if($result->num_rows > 0) //LINE 165 <------- ERROR!!
{
$body = array();
//output data for each row
while($row = $result->fetch_assoc())
{
array_push($body, $row);
}

$json =
[
'header' =>
[
'msg' => "OK - Everything is working",
'code' => 200
],
'body' => $body
];
echo json_encode($json, JSON_PRETTY_PRINT);
}
else
{
$json =
[
'header' =>
[
'msg' => $conn->error,
'code' => 400
],
'body' => []
];
echo json_encode($json, JSON_PRETTY_PRINT);
}
$conn->close();
}
?>

Answer

PDO::query() returns a PDOStatement object, or FALSE on failure, so you should write row 165 like this:

if($result && $result->num_rows > 0)
Comments