繁体   English   中英

当我尝试从PHP对象/数组返回值时,出现500错误。 但是可以返回所有对象

[英]I get the 500 error when I try to return a value from PHP object/array. But it's ok return all the object

我正在尝试在Laravel中创建一个简单的应用程序,该应用程序可以从数据库发送和获取注释。

我在AJAX中同时使用PHP和JS。 但是,当我尝试获取完整的注释对象时:

PHP

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

效果很好:

[{…}]
  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)

这正是我期望看到的完整的PHP对象。 但是当我尝试返回或仅使用同一对象的单个属性时,出现了500错误...

return $comment->id;

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

我是PHP的初学者,因此应该是一个非常简单的错误。

尝试这个:

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

您不需要json_decode()DB :: table()...调用的返回值。

要检索单行,应使用first()而不是get()

$comment = DB::table('comments')->where('id', $id)->first();
echo $comment->id;

https://laravel.com/docs/5.7/queries

由于json_decode()返回一个数组,而不是一个对象,因此出现错误500。 因此,要使用数组语法而不是对象运算符来访问数据:

return $comment['id']

您可以使用

$comment = DB::table('comments')->where('id', $id)->first();
return $comment->id;

要么

$comment = DB::table('comments')->where('id', $id)->get();
return $comment[0]->id;

如果在获取数据后使用json_decode,则对象将转换为数组。 因此,您必须使用$ arrayname ['keyname']来获取数据。

暂无
暂无

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

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