php - json 中缺少字段时无法更新数据库

标签 php mysql json laravel-5.1

我正在制作一个 api,可以帮助用户根据输入数据更新他们的信息。但是当输入 json 有字段“密码”时,它将成功更新,但是当 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;
    }

谢谢。

最佳答案

这里有问题的代码是:

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

检查看看是什么

isset($data['password'])

在 if 语句之外返回,如果 JSON 中存在密码并且没有给您一个听起来像您期望的问题,但是检查该语句本身是否为 false 而没有 if声明,确保它不会仍然跳入其中,它似乎是您寻找 'password'

的唯一地方

关于php - json 中缺少字段时无法更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522718/

相关文章:

php - mysql查询在BETWEEN中查找记录并列出是否存在

php - 在 laravel 5.6 中迁移时如何检查 mongo 集合是否存在?

php mysql where 语句 with AND 返回 true 即使第二个条件为 false

mysql - 获取每个不同客户 ID 中的最后一列

javascript - 使用 json 和 angularJs 访问范围内的嵌套菜单项

json - 如何测试期望通过 POST 请求接收 JSON 数组的 Controller 操作?

php - 复选框仍选中后退按钮,但没有 “checked”属性

mysql - SequelizeJS - 包含带有 hasMany + joinTableName 的表。笛卡尔积

php - 连接时 Google 图表仅显示 MySQL 的一项?

javascript - 这里是 Node.js 的新手。如何正确从 subreddit 顶部获取 JSON?