您好,登录后才能下订单哦!
这期内容当中小编将会给大家带来有关使用php怎么往mysql中批量插入数据,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
方法一、使用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循环插入耗费的时间:
| 条数 | 时间 (单位:秒) | 
|---|---|
| 10 | 0.011 | 
| 1000 | 0.585 | 
| 10000 | 5.733 | 
| 100000 | 60.587 | 
方法二、使用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循环插入节约了很多时间
| 条数 | 时间 (单位:秒) | 
|---|---|
| 10 | 0.006 | 
| 1000 | 0.025 | 
| 10000 | 0.131 | 
| 100000 | 1.23 | 
上述就是小编为大家分享的使用php怎么往mysql中批量插入数据了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。