I am making an api that can help the user update their information by following the input. But when there is a password field at json input, it will be updated successfully, but when json does not have this field, I cannot update the data in the database. This is the code I used to update the data:
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!']); } }
This is json when everything is working fine:
$postData = '{ "UserId" : "1", "password":"12345", "UserName": "minhkhang", "Address": "11/200" }'
This is json that will throw an error because the password field is missing:
$postData = '{ "UserId" : "1", "UserName": "minhkhang", "Address": "11/200" }'
This is the code I used to create the update line after json input:
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; }
Thanks.