0

I had main file with my plugin and the another file with sql command. In the second file I create two tables and write data to one of them. But I have problem with. In my private computer everything works good but on external server not. How can I optimize command below I have a 700 pieces insert like this:

$wpdb->insert( 
    $ow_table_adres, 
    array( 
        'id' => '', 
        'address' => 'test', 
        'kod' => '096-024', 
        'number' => '4'
    ) 
);
1
  • 1
    What fails? How does it fail? Do you have debugging information? What do your server logs say? I routinely run queries like that (with $wpdb->query not $wpdb->insert, which is helper function overload but that is beside the point) with no issue. I am pretty sure this is specific to your server, and I am guessing it is a timeout. Commented Dec 18, 2013 at 15:00

1 Answer 1

3

To optimize the query, instead of use $wpdb->insert is possible to use $wpdb->query and use a single query that insert all the items.

In fact, according to MySQL documentation:

If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements

So, if you have an array $all_items where every array item is an array having 'address', 'kod' and 'number' items, something like:

$all_items = array(

  array( 'address' => 'test', 'kod' => '096-024', 'number' => '4' ), 

  array( 'address' => 'test2', 'kod' => '096-025', 'number' => '5' ), 

  array( 'address' => 'test3', 'kod' => '096-026', 'number' => '6' ),  

);

then you can

$q = "INSERT INTO $ow_table_adres (address, kod, number) VALUES ";

foreach ( $all_items as $an_item ) {
  $q .= $wpdb->prepare(
    "(%s, %s, %d),",
    $an_item['address'], $an_item['kod'], $an_item['number']
  );
}

$q = rtrim( $q, ',' ) . ';';

$wpdb->query( $q );
3
  • Can you also add this array to solution ? Commented Dec 18, 2013 at 15:21
  • Can you write how should be look this array $all_items for many row ? Commented Dec 18, 2013 at 15:24
  • @PrzemysławSuszek added. Commented Dec 18, 2013 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.