I am making an api that can help user update their info follow the input data. But when in input json have field "password" it will update successfully but when json don't have this field i can not update data in database. This is code i used to update 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 the json when everything work fine:
$postData = '{ "UserId" : "1", "password":"12345", "UserName": "minhkhang", "Address": "11/200" }'
This is the json which will cause error because it is missing password field:
$postData = '{ "UserId" : "1", "UserName": "minhkhang", "Address": "11/200" }'
This is code i used to make update string follow input 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;
}
Thank you.
The code in question here is:
if(isset($data['password'])){
$data['password'] = bcrypt($data['password']);
}
Check to see what
isset($data['password'])
is returning outside the if statement, if it is true for password being present in the JSON and not giving you an issue that sounds like what you'd expect, however check to see if that statement by itself is false without the if statement, make sure it isn't still jumping into that, it seems to be the only place your looking for 'password'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With