dongtiannai0654 2018-09-16 02:22
浏览 125
已采纳

当我尝试从PHP对象/数组返回一个值时,我收到500错误。 但是可以归还所有对象

I'm trying to create a simple application in Laravel that sends and gets comments from the database.

I'm using both PHP and JS with AJAX. But when I try to get the full comment object:

PHP

    public function UpdateComment(Request $request){
        $id = $request->id;
        $jsonCode = DB::table('comments')->where('id', $id)->get();
        $comment = json_decode($jsonCode);
        return $comment
    }

Works well:

[{…}]
  0:
   author_id: 6
   comment_date: "2018-09-15 09:53:01"
   comment_text: "23423434234"
   history: ""
   id: 60
   last_update: "2018-09-15 00:00:00"
  >proto__: Object
  length: 1
>proto__: Array(0)

This is exactly what I expected to see, the full PHP object. But when I try to return or simply use a single attribute of this same object, I got a 500 error...

return $comment->id;

.

POST http://laravelhost/update-comment 500 (Internal Server Error)

I'm a beginner in PHP, so it should be a very simple error.

  • 写回答

4条回答 默认 最新

  • duanli9001 2018-09-17 04:34
    关注

    You are getting error 500 because json_decode() returns an array, not an object. So to access your data use array syntax, instead of object operator:

    return $comment['id']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题