How to insert more than one row of data into a table at one time

I would like to populate a custom table, with more than one row of data at one time. If I delete the second array, it will insert one row of data. It won’t add both rows at the same time though. How do I insert both rows at the same time? My code:

function mp_install_name_data() {
    global $wpdb;
    $table_name = $wpdb->prefix . "names";

    $wpdb->insert(
        $table_name,
        array(
            'id' => '1',
            'name' => 'matt',
            'age' => '20',
            'point_one' => '0.45',
            'point_two' => '0.22'     
        ),

         array(
            'id' => '2',
            'name' =>'james',
            'age' => '6',
            'point_one' => '0.27',
            'point_two' => '0.17'  
        )
    );  

         }

3 Answers
3

You could use a foreach loop –

function mp_install_name_data() {
    global $wpdb;
    $table_name = $wpdb->prefix . "names";

    $rows = array(
        array(
            'id' => '1',
            'name' => 'matt',
            'age' => '20',
            'point_one' => '0.45',
            'point_two' => '0.22'     
        ),
        array(
            'id' => '2',
            'name' =>'james',
            'age' => '6',
            'point_one' => '0.27',
            'point_two' => '0.17'  
        )
    );

    foreach( $rows as $row )
    {
        $wpdb->insert( $table_name, $row);  
    }
}

Leave a Comment