Codeigniter Insert Array to Database Codeigniter Insert Array to Database codeigniter codeigniter

Codeigniter Insert Array to Database


you can't save array in to database. You can convert it in to string using implode() and whenever you needed then convert it back in array using explode(). Like below

$phone=implode(',',$this->input->post('phone'));$form_data = array(        'first_name' => $this->input->post('first_name'),        'last_name' => $this->input->post('last_name'),        'phone' => $phone        );

OR

You can convert it to json string and when you needed convert back to Array Like below:

$phone = json_encode($this->input->post('phone'));

Convert back to array

$phone = json_decode($phone, TRUE);


Modify your function as below and it will works like charm,

function SaveForm($form_data)    {        foreach ($form_data as $contact)        {            $data[] = array(                'first_name' => $contact['first_name'],                'last_name' => $contact['last_name'],                'phone' => $contact['phone']                );        }        $this->db->insert_batch('customers', $data);         if ($this->db->affected_rows() > 0)        {            return TRUE;        }        return FALSE;    }

Modified:

Oh, yes you have to edit para array that you passed to SaveForm function.Please use following code, ignore above code:

    foreach($_POST['first_name'] as $key=>$fname)     {        $form_data[] = array(            'first_name' => $_POST['first_name'][$key],            'last_name' => $_POST['last_name'][$key],            'phone' => $_POST['phone'][$key],            );    }function SaveForm($form_data)  {    $this->db->insert_batch('customers', $data);     if ($this->db->affected_rows() > 0)    {        return TRUE;    }    return FALSE;  }


In controller

$phone = $_POST['phone'];//this will store data as array. Check image 02$form_data = array(    'first_name' => $this->input->post('first_name'),    'last_name' => $this->input->post('last_name'),    'phone' => $phone,//some times it works with '$phone');

In Model

function SaveForm($form_data){    $this->db->insert('customers', $form_data);    if ($this->db->affected_rows() == '1')    {        return TRUE;    }    else    {        return FALSE;    }}

Tested

Image 01 (My form)

01

Image 02 (After Submitted)

enter image description here