PHP注意:尝试获取非对象的属性(JSON)

时间:2016-09-13 22:28:14

标签: php mysql sql json request

我有一个问题让我头疼了一整天...... 我正在尝试检索我的JSON对象,但它无法检索数据。

我正在提出GET请求。 如果'id'为空,则应检索我的数据库(PHPMyAdmin)的arraylist中的所有笔记。有什么想法吗?

我得到的错误是:

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": []
        }

这是代码     

          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();
}
     ?>

1 个答案:

答案 0 :(得分:2)

PDO::query()返回PDOStatement对象,如果失败则返回FALSE,因此您应该像这样编写第165行:

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