分享一下php+mysqli批量添加的方法
<?php
const DB_SERVERNAME = '數(shù)據(jù)庫地址';
const DB_USERNAME = '用戶名';
const DB_PASSWORD = '密碼';
const DB_DBNAME = '庫名';
getData();
function getData(){
$table = '表名';
$con = @mysqli_connect(DB_SERVERNAME,DB_USERNAME,DB_PASSWORD);
mysqli_select_db($con,DB_DBNAME);
$conn = new mysqli(DB_SERVERNAME, DB_USERNAME, DB_PASSWORD, DB_DBNAME);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 要批量添加的二維數(shù)組
$array = [];
if(!empty($array)){
//每次執(zhí)行500條
$splitNum = 500;
foreach(array_chunk($array, $splitNum) as $values){
$sql = insertBatch($table, array('app_flag', 'user_add', 'user_sub'), $values);
if ($conn->query($sql) === TRUE) {
echo " 新記錄插入成功 " . PHP_EOL;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}else{
echo '數(shù)組為空';
}
$con->close();
}
function insertBatch($table, $keys, $values, $sqltype = 'INSERT'){
$str = " ";
foreach($values as $k => &$v){
$app_flag = addslashes($v['app_flag']);
$user_add = addslashes($v['user_add']);
$user_sub = addslashes($v['user_sub']);
$str .= "(";
$str .= " '$app_flag','$user_add','$user_sub'";
$str .= "),";
}
$str = rtrim($str, ',');
return $sqltype.' INTO `'.$table.'` (`'.implode('`, `', $keys).'`) VALUES '. $str;
}
如果還需要了解批量更新的話,可以參考下我的另一篇文章
【php+mysqli批量更新簡單易懂】
http://www.reibang.com/p/d72c1b705070?v=1694490184191
希望可以幫助到大家