php批量更新mysql中的数据

php批量修改数据到mysql数据库中:

public function doBatchModify($data=[],$table='user'){
        $userModel = new \Common\Model\UserModel();
        $data = array(
            9 =>  array('name'=>'张三','password'=>1,'true_name'=>'张三'),
            10 => array('name'=>'李四','password'=>2,'true_name'=>'李四'),
            14 => array('name'=>'王五','password'=>3,'true_name'=>'王五'),
            15 => array('name'=>'赵六','password'=>4,'true_name'=>'赵六'),
            16 => array('name'=>'钱七','password'=>5,'true_name'=>'钱七'),
            17 => array('name'=>'孙八','password'=>6,'true_name'=>'孙八')
        );
        if(count($data)==0 || empty($table)) exit('参数缺少');
        //获取所有的id
        $data_keys = array_keys($data);

        $col = $userModel->query("SHOW COLUMNS FROM `user`");
        $cols = [];
        array_map(function($value) use(&$cols){
            $cols[] = $value['field'];
        },$col);
        //拼接批量更新sql语句
        $sql = "UPDATE {$table} SET ";
        //合成sql语句
        foreach ($data[$data_keys[0]] as $key => $value) {
            if(!in_array($key,$cols)) continue;
            $sql .= "{$key} = CASE id ";
            foreach ($data as $k=>$v) {
                $sql .= sprintf("WHEN %d THEN '%s' ", $k, $v[$key]);
            }
            $sql .= "END, ";
        }
        //把最后一个,去掉
        $sql = substr($sql, 0, strrpos($sql,','));

        //合并所有id
        $ids = implode(',', $data_keys);
        //拼接sql
        $sql .= " WHERE id IN ({$ids})";
        dump($userModel->execute($sql));
    }

 

posted @ 2018-11-28 11:50  tatasix  阅读(2184)  评论(0编辑  收藏  举报