上一节的添加了一条数据,批量添加只需要foreach循环遍历添加即可
代码如下:<?php
//绑定参数
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$author);
//单条插入
//$name='java基础教程';
//$author='smile4';
//$stmt->execute();
//批量插入
$data=array(
array('php预处理批量添加教程1','smile'),
array('php预处理批量添加教程2','smile'),
array('php预处理批量添加教程3','smile'),
);
foreach ($data as $row){
$name=$row[0];
$author=$row[1];
$stmt->execute();
}
完整代码如下:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/5 0005
* Time: 上午 9:23
*/
header("Content-Type:text/html;charset=utf-8");
//mysql:host:localhost;port=3306;dbname=php;charset=utf-8
$dbms='mysql';
$host='localhost';
$port='3306';
$dbname='php';
$charset='utf-8';
//用户名与密码
$user='root';
$pwd='root';
$dsn="$dbms:host=$host;port=$port;dbname=$dbname;charset=$charset";
try{
$pdo=new PDO($dsn,$user,$pwd);
//预处理sql语句
$stmt=$pdo->prepare("insert into book(name,author)values(?,?)");
//绑定参数
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$author);
//单条插入
//$name='java基础教程';
//$author='smile4';
//$stmt->execute();
//批量插入
$data=array(
array('php预处理批量添加教程1','smile'),
array('php预处理批量添加教程2','smile'),
array('php预处理批量添加教程3','smile'),
);
foreach ($data as $row){
$name=$row[0];
$author=$row[1];
$stmt->execute();
}
//$sql='select *from book';
//$result=$pdo->query($sql);
//$row=$result->fetchAll(PDO::FETCH_ASSOC);
//echo "
";
//print_r($row);
//echo "
";}catch (PDOException $exception){
echo $exception->getMessage().'
';
}
执行结果展示:
execute()函数里也可以添加参数,参数类型为数组,数组中的元素个数必须与占位符个数相同
全部代码展示:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/5 0005
* Time: 上午 9:23
*/
header("Content-Type:text/html;charset=utf-8");
//mysql:host:localhost;port=3306;dbname=php;charset=utf-8
$dbms='mysql';
$host='localhost';
$port='3306';
$dbname='php';
$charset='utf-8';
//用户名与密码
$user='root';
$pwd='root';
$dsn="$dbms:host=$host;port=$port;dbname=$dbname;charset=$charset";
try{
$pdo=new PDO($dsn,$user,$pwd);
//预处理sql语句
$stmt=$pdo->prepare("insert into book(name,author)values(?,?)");
//绑定参数
//$stmt->bindParam(1,$name);
//$stmt->bindParam(2,$author);
//单条插入
//$name='java基础教程';
//$author='smile4';
//$stmt->execute();
//批量插入
$data=array(
array('php预处理批量添加教程1','smile'),
array('php预处理批量添加教程2','smile'),
array('php预处理批量添加教程3','smile'),
);
foreach ($data as $row){
// $name=$row[0];
// $author=$row[1];
$stmt->execute($row);
}
//$sql='select *from book';
//$result=$pdo->query($sql);
//$row=$result->fetchAll(PDO::FETCH_ASSOC);
//echo "
";
//print_r($row);
//echo "
"}catch (PDOException $exception){
echo $exception->getMessage().'
';
}
;
注意:分析上面提到的execute()代码可以知道使用“?”占位符传递多条数据时使用的数组时索引数组,
也就是
array(
array('php预处理批量添加教程1','smile'),
array('php预处理批量添加教程2','smile'),
array('php预处理批量添加教程3','smile'),
);类型的数组
如果是使用(:参数名称)的占位符,多条插入时需要使用关联数组,即数组索引是具体的有类型的数据
例如:
array(
array("name"=>'php预处理批量添加教程1',"author"=>'smile'),
array("name"=>'php预处理批量添加教程1',"author"=>'smile'),
array("name"=>'php预处理批量添加教程1',"author"=>'smile')
);