mardi 29 décembre 2015

Can not update database when missing field in json

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire