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;
}