PHP操作MySQL批量Update的写法,各框架通用防注入版

作者: 怀老师 | 来源:发表于2020-08-27 17:53 被阅读0次

    使用别人的扩展遇到了问题,发现没有做SQL注入的处理。我又写了个轮子,根据自己需求扩展了下,有需要可以直接取用,仅需写明来源。

    <?php
    
    
    namespace App\Utils;
    
    
    use Illuminate\Support\Facades\DB;
    
    class UpdateBatch
    {
    
        /***
         * @param string $table 表名
         * @param array $values 更新字段
         * @param string $index key值
         * @param bool $raw 是否特殊处理
         * @return bool|int
         */
        public static function update(string $table, array $values, string $index, bool $raw = false)
        {
            if (!count($values)) {
                return false;
            }
    
            if (!isset($index) || empty($index)) {
                return false;
            }
    
            $sets = $bindings = [];
            $updateSql = "UPDATE `" . config('database.connections.mysql.prefix').$table . "` SET " ;
    
            $data = array_keys($values[0]);
            $data = array_diff($data,[$index]);
            foreach ($data as $field) {
                $setSql = '`' . $field . '` = (CASE ';
                foreach ($values as $key => $val) {
                    if($raw){
                        //特殊处理,给需要自增的字段用
                        $setSql .= 'WHEN `' . $index . '` = ? THEN '.$field.'+? ';
                    }else{
                        $setSql .= 'WHEN `' . $index . '` = ? THEN ? ';
                    }
                    $value = (is_null($val[$field]) ? 'NULL' : $val[$field]);
                    $bindings[] = $val[$index];
                    $bindings[] = $value;
                }
                $setSql .= 'ELSE `'.$field.'` END) ';
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ',$sets);
    
            $whereIn = array_column($values,$index,null);
            $bindings = array_merge($bindings,$whereIn);
            $whereIn = rtrim(str_repeat('?,',count($whereIn)),',');
    
            $query = rtrim($updateSql,', ') . " WHERE `$index` IN(" . $whereIn . ");";
            return DB::update($query,$bindings);
        }
    }
    

    使用方法

    <?php
    use App\Utils\UpdateBatch;
    class A{
        public function b(){
            $updateArr[] = [
                            'id'=>1,
                            'b' => 2,
                            'c' => 3,
                        ];
          //批量更新
           $index = 'id';//以此key为条件更新
            $table_name = 'tableName';//要更新的表
            $raw = true;//非必传,传true,则sql类似update tableName set b=b+2;不传或者false还是走绑定值。
            UpdateBatch::update($table_name, $updateArr, $index,$raw);
      }
    }

    相关文章

      网友评论

        本文标题:PHP操作MySQL批量Update的写法,各框架通用防注入版

        本文链接:https://www.haomeiwen.com/subject/mjvcsktx.html