我正在制作一个api,可以帮助用户按照输入数据更新他们的信息.但是当输入json有字段"password"时它会成功更新但是当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; }
谢谢.