Wordpress w wpdb. Insertar Varios Registros


¿Hay alguna manera de lograr lo siguiente en Wordpress con $wpdb->insert o

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

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

...etc

Author: djt, 2012-09-11

5 answers

OK, me di cuenta!

Configurar matrices para Valores Reales, y Marcadores de posición

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

La consulta inicial:

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

Luego recorra los valores que desea agregar e insértelos en los arrays apropiados:

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

Luego agregue estos bits a la consulta inicial:

$query .= implode(', ', $place_holders);
$wpdb->query( $wpdb->prepare("$query ", $values));
 58
Author: djt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-11 17:22:38

También puede usar esta manera para construir la consulta:

$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 );
 13
Author: Philipp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-24 18:39:00

Me he encontrado con este problema y decidí construir una función más mejorada mediante el uso de respuesta aceptada también:

/**
 * 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
    $values = array();
    $place_holders = array();
    $query = "";
    $query_columns = "";

    $query .= "INSERT INTO {$wp_table_name} (";

            foreach($row_arrays as $count => $row_array)
            {

                foreach($row_array as $key => $value) {

                    if($count == 0) {
                        if($query_columns) {
                        $query_columns .= ",".$key."";
                        } else {
                        $query_columns .= "".$key."";
                        }
                    }

                    $values[] =  $value;

                    if(is_numeric($value)) {
                        if(isset($place_holders[$count])) {
                        $place_holders[$count] .= ", '%d'";
                        } else {
                        $place_holders[$count] .= "( '%d'";
                        }
                    } else {
                        if(isset($place_holders[$count])) {
                        $place_holders[$count] .= ", '%s'";
                        } else {
                        $place_holders[$count] .= "( '%s'";
                        }
                    }
                }
                        // mind closing the GAP
                        $place_holders[$count] .= ")";
            }

    $query .= " $query_columns ) VALUES ";

    $query .= implode(', ', $place_holders);

    if($wpdb->query($wpdb->prepare($query, $values))){
        return true;
    } else {
        return false;
    }

}

Fuente: https://github.com/mirzazeyrek/wp-multiple-insert

 5
Author: motto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-20 12:19:08

Esto es un poco tarde, pero también podrías hacerlo así.

    global $wpdb;
    $table_name = $wpdb->prefix . 'your_table';

    foreach ($your_array as $key => $value) {
          $result = $wpdb->insert( 
            $table_name, 
            array( 
              'colname_1' => $value[0], 
              'colname_2' => $value[1], 
              'colname_3' => $value[2], 
            ) 
          );
        }
  if (!$result) {
    print 'There was a error';
  }
 -3
Author: Wervada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-10 15:42:11

No es muy agradable, pero si sabes lo que estás haciendo:

require_once('wp-load.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);  
@mysql_select_db(DB_NAME) or die();
mysql_query("INSERT into TABLE ('column1', 'column2', 'column3') VALUES 
                               ('value1', 'value2', 'value3'), 
                               ('otherval1', 'otherval2', 'otherval3'),
                               ('anotherval1', 'anotherval2', 'anotherval3)");
 -8
Author: gion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-27 12:42:48