Michael Grigsby
Michael Grigsby

Reputation: 12163

Inserting multiple arrays into a mysql database

Each input->post is a key/value array. Each value inside of each array matches up to the rest of the array values. So the first row in the database insertion will be all of the data from all of the array's key 0. The second will be 1 and so on and so on. How would I take all of the data from the post arrays and insert them into the database using this method?

$selected_size = $this->input->post('selected_size');
        $product_id = $this->input->post('product_id');
        $product_name = $this->input->post('product_name');
        $product_color = $this->input->post('product_color');

        $cookie_id = $this->input->cookie("cookie_id");
        $q1 = $this->db->query("SELECT * FROM default_cart_temp
                                WHERE cookie_id = '$cookie_id'
                                AND is_paid = 'No'");
        if ($q1->num_rows() > 0) {

        } else {
            print_r($selected_size);
            /*$data = array('selected_size' => $selected_size,
                          'product_id' => $product_id,
                          'product_name' => $product_name,
                          'product_color' => $product_color);

$this->db->insert('mytable', $data);*/
        }

Upvotes: 3

Views: 391

Answers (1)

MrCode
MrCode

Reputation: 64526

Assuming your insert() method takes an associative array and then builds and executes the insert statement:

foreach($product_id as $key => $value)
{
    $data = array(
        'selected_size' => $selected_size[$key],
        'product_id' => $value,
        'product_name' => $product_name[$key],
        'product_color' => $product_color[$key]
    );

    $this->db->insert('mytable', $data);
}

By using a foreach on one of the arrays and obtaining the key on each iteration, you can use the same key variable to access the corresponding element in each other array.

Upvotes: 3

Related Questions