Cannot update database if no field in json

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.

+5
source share
1 answer

This code has:

 if(isset($data['password'])){ $data['password'] = bcrypt($data['password']); } 

Check that

 isset($data['password']) 

returns outside the if statement if this is true for the password present in JSON and does not give you a problem that sounds like you expected, however check if this statement is false without if, make sure it doesn't jump into this, this is the only place you look for 'password'

+2
source

Source: https://habr.com/ru/post/1239463/


All Articles