即使有一个可接受的答案,它也可以为每个插入使用单独的查询。
对于仅在一个查询中插入数据而言,这可能是一个更好的解决方案:
<?php
/**
* A method for inserting multiple rows into the specified table
*
* Usage Example:
*
* $insert_arrays = array();
* foreach($assets as $asset) {
*
* $insert_arrays[] = array(
* \'type\' => "multiple_row_insert",
* \'status\' => 1,
* \'name\'=>$asset,
* \'added_date\' => current_time( \'mysql\' ),
* \'last_update\' => current_time( \'mysql\' ));
*
* }
*
* wp_insert_rows($insert_arrays);
*
*
* @param array $row_arrays
* @param string $wp_table_name
* @return false|int
*
* @author Ugur Mirza ZEYREK
* @source http://stackoverflow.com/a/12374838/1194797
*/
function wp_insert_rows($row_arrays = array(), $wp_table_name) {
global $wpdb;
$wp_table_name = esc_sql($wp_table_name);
// Setup arrays for Actual Values, and Placeholders
$place_holders = [];
$row = implode(\', \', array_keys($row_arrays));
$values = array_values($row_arrays);
foreach (array_values($row_arrays) as $key => $param) {
if(is_numeric($param)) {
if($key == 0){
array_push($place_holders, " \'%d\'");
} else {
array_push($place_holders, ", \'%d\'");
}
} else {
if($key == 0){
array_push($place_holders, " \'%s\'");
} else {
array_push($place_holders, ", \'%s\'");
}
}
}
$params = implode(\'\', $place_holders);
$query = "INSERT INTO {$wp_table_name} (" . $row . ") VALUES (" . $params . ")";
if($wpdb->query($wpdb->prepare($query, $values))){
return true;
} else {
return false;
}
}
资料来源:
https://github.com/mirzazeyrek/wp-multiple-insert