Sanoj Dushmantha
Sanoj Dushmantha

Reputation: 1015

Loop through batch Codeigniter

I am inserting data to the database using insert_batch() function.

I want to split the process. I mean if I want to create 10,000 serial numbers. but 1,000 rows at a time, it should run the create process 10 times in a loop.

How can I do that?

    $serial_numbers  = $this->serial_numbers_model->generate_serial_numbers($product_id, $partner_id, $serial_number_quantity, $serial_number_start);
    $issued_date     = date("Y-m-d H:i:s");
    $inserted_rows   = 0;

    foreach ($serial_numbers as $sn) {
        $check_number = $this->serial_numbers_model->generate_check_number();
        $first_serial_number = reset($serial_numbers);
        $last_serial_number = end($serial_numbers);
        $inserted_rows++;

        $insert_data[] = array(
            'partner_id'            => $partner_id,
            'product_id'            => $product_id,
            'check_number'          => $check_number,
            'serial_number'         => $sn,
            'issued_time'           => $issued_date,
            'serial_number_status'  => CREATE_STATUS
        );
    }

    $this->serial_numbers_model->insert_batch($insert_data);
}

Upvotes: 1

Views: 172

Answers (1)

Don't Panic
Don't Panic

Reputation: 14520

Probably your serial_numbers_model->insert_batch() is just a wrapper around Codeigniter's native insert_batch()? The code below uses the native one for clarity, replace it with yours as required.

// Track how many in your batch, and prepare empty batch array
$count = 0;
$insert_data = [];

foreach ($serial_numbers as $sn) {

    // ... your code, prepare your data, etc ...

    $count++;

    $insert_data[] = array(
        // ... your data ...
    );

    // Do you have a batch of 1000 ready?
    if ($count === 1000) {

        // Yes - insert it
        $this->db->insert_batch('table', $insert_data);
        // $this->serial_numbers_model->insert_batch($insert_data);

        // Reset the count, and empty the batch, ready to start again
        $count = 0;
        $insert_data = [];
    }
}

// Watch out!  If there were 1001 serial numbers, the first 1000 were handled, 
// but the last one hasn't been inserted!
if (sizeof($insert_data)) {
    $this->db->insert_batch('table', $insert_data);
}

Upvotes: 1

Related Questions