• pdo一次插入多条数据的2种实现方式


    1).一个sql插入多个值,防注入处理放在获取到值的时候使用htmlspecialchars(addslashes($params ));

            try{
    
                foreach($params as $k=> $item) {
                    if($k==0){
                        $sql ="insert into tr_user(empno,username,email,create_time,update_time) VALUES('".$item['empno']."','".$item['username']."','".$item['email']."',".$item['create_time'].",".$item['update_time'].")";
                    }else{
                        $sql .=",('".$item['empno']."','".$item['username']."','".$item['email']."',".$item['create_time'].",".$item['update_time'].")";
                    }
                }
                $stmt = $this->pdo->prepare($sql);
                $res = $stmt->execute();
                if($res){
                    return true;
                }else{
                    return false;
                }
    
            }catch (Exception $e){
                var_dump($e->getMessage());
                return false;
            }
    
    

    2). 通过预处理绑定数据,防sql注入 (注释语句)

        try{
                $sql = "insert into tr_user(empno,username,email,create_time,update_time) VALUES (:empno,:username,:email,:create_time,:update_time)";
                $stmt = $this->pdo->prepare($sql);
                foreach($params as $item){
                    $stmt->bindParam(':empno',$item['empno']);
                    $stmt->bindParam(':username',$item['username']);
                    $stmt->bindParam(':email',$item['email']);
                    $stmt->bindParam(':create_time',$item['create_time']);
                    $stmt->bindParam(':update_time',$item['update_time']);
                    $res = $stmt->execute();
                }
                if($res){
                    return true;
                }else{
                    return false;
                }
    
            }catch (Exception $e){
                var_dump($e->getMessage());
                return false;
            }
    
    
  • 相关阅读:
    228. Summary Ranges
    324. Wiggle Sort II
    42. Trapping Rain Water
    工作之后
    279. Perfect Squares
    391. Perfect Rectangle
    351. Android Unlock Patterns
    246. Strobogrammatic Number
    [LeetCode] 75. Sort Colors Java
    [Java] 80. Remove Duplicates from Sorted Array II Java
  • 原文地址:https://www.cnblogs.com/xinxinmifan/p/pdo_mulit_insert_learning.html
Copyright © 2020-2023  润新知