Wordpress $wpdb.插入多条记录

2022-08-30 13:49:48

有没有办法在Wordpress中使用或$wpdb->insert

$wpdb->query($wpdb->prepare)):

INSERT into TABLE (column1, column2, column3) 
VALUES
('value1', 'value2', 'value3'),
('otherval1', 'otherval2', 'otherval3'),
('anotherval1', 'anotherval2', 'anotherval3')

...等


答案 1

好吧,我想通了!

设置实际值和占位符的数组

$values = array();
$place_holders = array();

初始查询:

$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";

然后循环访问要添加的值,并将它们插入到相应的数组中:

foreach ( $_POST as $key => $value ) {
     array_push( $values, $value, $order_id );
     $place_holders[] = "('%d', '%d')" /* In my case, i know they will always be integers */
}

然后将这些位添加到初始查询中:

$query .= implode( ', ', $place_holders );
$wpdb->query( $wpdb->prepare( "$query ", $values ) );

答案 2

您还可以使用这种方式构建查询:

$values = array();

// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
    $values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}

$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";
$query .= implode( ",\n", $values );

推荐