Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress $wpdb. Insert Multiple Records

Is there any way to accomplish the following in Wordpress with $wpdb->insert or

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

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

...etc

like image 628
djt Avatar asked Sep 11 '12 16:09

djt


2 Answers

OK, I figured it out!

Setup arrays for Actual Values, and Placeholders

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

the initial Query:

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

Then loop through the the values you're looking to add, and insert them in the appropriate arrays:

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 */
}

Then add these bits to the initial query:

$query .= implode( ', ', $place_holders );
$wpdb->query( $wpdb->prepare( "$query ", $values ) );
like image 198
djt Avatar answered Oct 24 '22 10:10

djt


You can also use this way to build the query:

$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 );
like image 19
Philipp Avatar answered Oct 24 '22 10:10

Philipp