我正在制作一个 api,可以帮助用户根据输入数据更新他们的信息。但是当输入 json 有字段“密码”时,它将成功更新,但是当 json 没有这个字段时,我无法更新数据库中的数据。这是我用来更新数据的代码:
public function updateUserInfo(Request $request){
$postData = $request->all();
$data = json_decode($postData['postData'], true);
if(isset($data['password'])){
$data['password'] = bcrypt($data['password']);
}
$popData = $data['UserId'];
unset($data['UserId']);
$updateInfo = array();
foreach($data as $info){
if($info != null){
$updateInfo[] = $info;
}
}
$result = DB::update(GeneralFunctions::makeUpdateString($data, 'User', ' UserId = '.$popData), $updateInfo);
if($result != null && $result == true){
return response()->json(['success'=>true, 'data'=>'Update Successful']);
}else{
return response()->json(['success'=>false, 'error'=>'We have encountered an error, try again later!']);
}
}
这是一切正常时的 json:
$postData = '{ "UserId" : "1", "password":"12345", "UserName": "minhkhang", "Address": "11/200" }'
这是将导致错误的 json,因为它缺少密码字段:
$postData = '{ "UserId" : "1", "UserName": "minhkhang", "Address": "11/200" }'
这是我用来使更新字符串跟随输入 json 的代码:
public static function makeUpdateString($keyvalarr, $table, $where){
$stringSQL = 'UPDATE '.$table. ' SET ' ;
foreach($keyvalarr as $fieldname => $updateval){
if($updateval != null){
$stringSQL .= $fieldname.' = ? , ';
}
}
$stringSQL = substr($stringSQL, 0, -2);
if($where != null){
$stringSQL .= 'WHERE '.$where;
}
return $stringSQL;
}
谢谢。
最佳答案
这里有问题的代码是:
if(isset($data['password'])){
$data['password'] = bcrypt($data['password']);
}
检查看看是什么
isset($data['password'])
在 if 语句之外返回,如果 JSON 中存在密码并且没有给您一个听起来像您期望的问题,但是检查该语句本身是否为 false 而没有 if声明,确保它不会仍然跳入其中,它似乎是您寻找 'password'
关于php - json 中缺少字段时无法更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522718/