zoukankan      html  css  js  c++  java
  • php批量更新mysql中的数据

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

    public function doBatchModify($data=[],$table='user'){
            $userModel = new CommonModelUserModel();
            $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));
        }
  • 相关阅读:
    BZOJ 2038: [2009国家集训队]小Z的袜子 (莫队)
    codevs 3981 动态最大子段和(线段树)
    ACM北大暑期课培训第八天
    ACM北大暑期课培训第七天
    ACM北大暑期课培训第六天
    ACM北大暑期课培训第五天
    ACM北大暑期课培训第四天
    HDU4403-模拟、数学
    HDU4296-ChengduOnling-贪心
    POJ3176-基础DP
  • 原文地址:https://www.cnblogs.com/crazytata/p/10031256.html
Copyright © 2011-2022 走看看