Skip to content

Instantly share code, notes, and snippets.

@sc0ttkclark
Created December 5, 2013 21:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sc0ttkclark/7814046 to your computer and use it in GitHub Desktop.
Save sc0ttkclark/7814046 to your computer and use it in GitHub Desktop.
Add bulk insert/replace capability to wpdb::insert / wpdb::replace without adding unnecessary overhead for normal single inserts
<?php
/**
* Helper function for insert and replace.
*
* Runs an insert or replace query based on $type argument.
*
* @access private
* @since 3.0.0
* @see wpdb::prepare()
* @see wpdb::$field_types
* @see wp_set_wpdb_vars()
*
* @param string $table table name
* @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
* A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
* @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
* @return int|false The number of rows affected, or false on error.
*/
function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
if ( !in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
return false;
}
$this->insert_id = 0;
$formats = $format = (array) $format;
$formatted_fields = array();
// Get first value for bulk check
$current_check = current( $data );
// Bulk handling
if ( is_array( $current_check ) ) {
$fields = array_keys( $current_check );
$rows = count( $data );
// Handle $data like a flat array
$data = new RecursiveIteratorIterator( new RecursiveArrayIterator( $data ) );
}
// Single handling
else {
$fields = array_keys( $data );
$rows = 1;
}
foreach ( $fields as $field ) {
if ( !empty( $format ) ) {
$form = ( $form = array_shift( $formats ) ) ? $form : $format[ 0 ];
}
elseif ( isset( $this->field_types[ $field ] ) ) {
$form = $this->field_types[ $field ];
}
else {
$form = '%s';
}
$formatted_fields[] = $form;
}
$values = "(" . implode( ",", $formatted_fields ) . ")";
// Bulk handling
if ( 1 < $rows ) {
$values = array_fill( 0, $rows, $values );
$values = implode( ",", $values );
}
$sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES " . $values;
return $this->query( $this->prepare( $sql, $data ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment