我是PHP编码的新手,我正在尝试使用Slim 3.我只是想编写一个添加函数来添加 fname,lname,address,email&年龄。 我一直收到错误:
"致命错误:在"
中的数组上调用带有Json()的成员函数
这是为了这一行:
"return $res->withJson(["person"=>$data],404)->withAddedHeader('Location',"/users/$id", ["text"=>"person does not exist"]);" after the "catch(PDOException $e) {".
提前致谢..
以下是代码:
<?php
/POST /persons : add a new person
$app->post('/persons', function ($req, $res){
try{
// check if all data is there
$data=$req->getParsedBody();
$filter = [
'fname' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => [
'regexp' => '/[a-zA-Z]+/'
]
],
'lname' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => [
'regexp' => '/[a-zA-Z]+/'
]
],
'address' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => [
'regexp' => '/[a-zA-Z]+/'
]
],
'email' => [
'filter' => FILTER_VALIDATE_EMAIL,
'options' => [
'regexp' =>'/[A-Z0-9._%+-]+@[A-Z0-9.-]+/'
]
],
'age' => [
'filter' => FILTER_VALIDATE_INT,
'options' => [
'regexp' => '/{1,100}'
]
]
];
$res = filter_var_array($data,$filter);
if(empty($data)){
return $res->withJson( ["error"=>
[ "text" => "The information provided is inadequate"]
],400);
}else
// ....
$sql = 'insert into person (fname, lname, address, email, age)values(:fname,:lname,:address,:email,:age)';
// prepare
$stmt =$this->db->prepare($sql);
// execute with values from $data
$stmt->execute(['fname'=>$res['fname'],'lname'=>$res['lname'],'address'=>$res['address'],'email'=>$res['email'],'age'=>$res['age']]);
// take lastinsertid and make a new header Location with it
$id = $this->db->lastInsertId();
// return a JSON saying all ok and new location
return $res->withJson(["person"=>$data],201)->withAddedHeader('Location',"/users/$id", ["text"=>"person added correctly"]);
}
catch(PDOException $e) {
return $res->withJson(["person"=>$data],404)->withAddedHeader('Location',"/users/$id", ["text"=>"person does not exist"]);
}
});
答案 0 :(得分:0)
$res = filter_var_array($data,$filter);
返回数组。数组类型没有方法withJson()
。这就是问题。您可能希望使用json_encode()
函数。
好的,然后做两件事:
#1。改变:
$res = filter_var_array($data,$filter);
到
$params = filter_var_array($data,$filter);
#2。改变:
$stmt->execute(['fname'=>$res['fname'],'lname'=>$res['lname'],'address'=>$res['address'],'email'=>$res['email'],'age'=>$res['age']]);
到
$stmt->execute([
'fname' => $params['fname'],
'lname' => $params['lname'],
'address' => $params['address'],
'email' => $params['email'],
'age' => $params['age']
]);