假如说我有这样一个表,我想往这个表里面插入大量数据
create table if not exists `user_info` (`id` int(11) not null auto_increment comment '自增主键',`name` varchar(255) not null default '' comment '姓名',`age` int(11) not null default '0' comment '年龄',primary key (`id`)) engine=innodb default charset=utf8 comment='用户信息表';
批量插入
方法一、使用for循环插入
在往mysql插入少量数据的时候,我们一般用for循环
$arr = [ ['name' => 'testname1','age' => 18,],['name' => 'testname2','age' => 19,],['name' => 'testname3','age' => 18,],];$servername = "localhost";$port = 3306;$username = "username";$password = "password";$dbname = "mytestdb";// 创建连接$conn = new mysqli($servername, $username, $password, $dbname, $port);// 检测连接if ($conn->connect_error) {die("connect failed: " . $conn->connect_error);} $costbegin = microtime(true);foreach($arr as $item) {$sql = sprintf("insert into user_info (name, age) values ( '%s', %d);", $item['name'], (int)$item['age']); if ($conn->query($sql) === true) {echo "insert success";} else {echo "error: " . $sql . "<br>" . $conn->error;}}$costend = microtime(true);$cost = round($costend - $costbegin, 3);var_dump($cost);$conn->close();
假如说要批量插入大量数据,如果还用for循环的办法插入是没有问题的,只是时间会比较长。对比一下插入少量数据与插入大量数据,使用上面的for循环插入耗费的时间:条数时间(单位:秒)
方法二、使用insert语句合并插入
mysql里面是可以使用insert语句进行合并插入的,比如
insert into user_info (name, age) values ('name1', 18), ('name2', 19);表示一次插入两条数据$arr = [ ['name' => 'testname1','age' => 18,],['name' => 'testname2','age' => 19,],['name' => 'testname3','age' => 18,],// 此处省略…………];$servername = "localhost";$port = 3306;$username = "username";$password = "password";$dbname = "mytestdb";// 创建连接$conn = new mysqli($servername, $username, $password, $dbname, $port);// 检测连接if ($conn->connect_error) {die("connect failed: " . $conn->connect_error);} $costbegin = microtime(true);if (!empty($arr)) {$sql = sprintf("insert into user_info (name, age) values ");foreach($arr as $item) {$itemstr = '( ';$itemstr .= sprintf("'%s', %d", $item['name'], (int)$item['age']);$itemstr .= '),';$sql .= $itemstr;}// 去除最后一个逗号,并且加上结束分号$sql = rtrim($sql, ',');$sql .= ';';if ($conn->query($sql) === true) {} else {echo "error: " . $sql . "<br>" . $conn->error;}}$costend = microtime(true);$cost = round($costend - $costbegin, 3);var_dump($cost);$conn->close();
下面看一下少量数据与大量数据的时间对比。从总体时间上,可以看出insert合并插入比刚才for循环插入节约了很多时间,效果很明显条数时间(单位:秒)
如果你觉得数组太大,想要减少sql错误的风险,也可以使用array_chunk将数组切成指定大小的块,然后对每个块进行insert合并插入.
更多php相关知识,请访问php教程!
以上就是php在mysql里批量插入数据(代码实例)的详细内容。