Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How do I use $wpdb->insert to insert multiple rows. Here is my code.

for($i=0; $i<=$urlCount; $i++) {
   $stat = $wpdb->insert(
            'POSTID' => $post->ID,
            'URL' =>   $_POST['url'.$i]

This code works only for the first insert (ie, when $i = 0 , when value is url_0 ). Sometimes the URL count will be more than 100 and sometimes it will be zero. So instead of writing the code for 100 times, I just want to have a simple loop that works for any number of records. Thats the reason I went for loop.

Thank you for the help.

The table structure is

share|improve this question
What is the structure of your table? I see no problem in your code. –  JohnnyPea Sep 2 '11 at 6:52
You might want to use $wpdb->prepare() for security reasons. See Codex. –  kaiser Sep 2 '11 at 13:26
CREATE TABLE WP_URLS ( POSTID BIGINT NOT NULL, URL VARCHAR(254) ); @johnnyPea –  Albin Joseph Sep 3 '11 at 4:27
@kaiser the $wpdb->insert() escapes the data as per the documentation. Still do we need to use $wpdb->prepare() ? –  Albin Joseph Sep 3 '11 at 4:34
@Albin Joseph You're right. I just took a look at the core and both insert & replace use the prepare fn. –  kaiser Sep 3 '11 at 21:52

1 Answer 1

up vote 1 down vote accepted

I guess the problem is a pretty simple one. You didn't show the whole code, but I guess the problem is that you're saving the insertion for some unknown reason as string into a var named $stat. Everytime you fill the var with a new query you're overwriting your var. You should use $stat .= $wpdb->insert( ...etc... ) instead. to append to your string. Don't forget to set the var to an empty string before the loop, so you can append: $stat = ''.

Another - imo better way - would be to use an array. Reason: You can easier debug the code. And pls read the comment i/t code.

$stats = array();
for( $i = 0; $i <= $urlCount; $i++ ) 
    $stats[] = array(
        'POSTID' => $post->ID,
        // are you really retrieving **ALL** your urls as "url1", "url2", etc. 
        // via some $_POST-ed form?
        'URL' =>   filter_var(

foreach ( $stats as $stat )
    $wpdb->insert( 'WP_URLS', $stat );
share|improve this answer
I just wanted to see if the insertion was successful or not and thats the reason I stored the $stat. Just to print the value. –  Albin Joseph Sep 5 '11 at 6:44
Thank you for the better way. I printed $_POST and it has values for ur1, url2 etc. –  Albin Joseph Sep 5 '11 at 6:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.