首頁  >  文章  >  後端開發  >  php在mysql裡批量插入資料(程式碼實例)

php在mysql裡批量插入資料(程式碼實例)

藏色散人
藏色散人轉載
2020-01-31 19:18:103478瀏覽

php在mysql裡批量插入資料(程式碼實例)

假如說我有這樣一個表,我想在這個表裡面插入大量資料

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循環插入耗費的時間:條數時間(單位:秒)

php在mysql裡批量插入資料(程式碼實例)

## 

 

方法二、使用insert語句合併插入

mysql裡面是可以使用insert語句進行合併插入的,例如

INSERT INTO user_info (name, age) VALUES (&#39;name1&#39;, 18), (&#39;name2&#39;, 19);表示一次插入两条数据

$arr = [ 
[
&#39;name&#39; => &#39;testname1&#39;,
&#39;age&#39; => 18,
],
[
&#39;name&#39; => &#39;testname2&#39;,
&#39;age&#39; => 19,
],
[
&#39;name&#39; => &#39;testname3&#39;,
&#39;age&#39; => 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 = &#39;( &#39;;
$itemStr .= sprintf("&#39;%s&#39;, %d", $item[&#39;name&#39;], (int)$item[&#39;age&#39;]);
$itemStr .= &#39;),&#39;;
$sql .= $itemStr;
}

// 去除最后一个逗号,并且加上结束分号
$sql = rtrim($sql, &#39;,&#39;);
$sql .= &#39;;&#39;;

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循環插入節約了很多時間,效果很明顯條數時間(單位:秒)

 

 

php在mysql裡批量插入資料(程式碼實例)

 

 

如果你覺得陣列太大,想要減少sql錯誤的風險,你也可以用array_chunk將陣列切成指定大小的區塊,然後對每個區塊進行insert合併插入.

更多php相關知識,請造訪

php教學

以上是php在mysql裡批量插入資料(程式碼實例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除