3

I have created a form in Codeigniter with a phone number field that dynamically is duplicated using javascript. So basically I can have one or more fields like this.

<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">

Then in my controller I have

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

Then I am saving this to my dabase like so

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

but obviously the code for 'phone' is wrong, I just cant figure out how to properly do this.

6 Answers 6

6

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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

function SaveForm($form_data)
{
    $batch_data = [];
    foreach ($form_data as $data) {
        $batch_data[] = [
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'phone' => $data['phone']
        ];
    }

    $this->db->insert_batch('customers', $batch_data);

    return $this->db->affected_rows() > 0;
}

3 Comments

Unfortunately this one is not working, and each line of the array is throwing and error Illegal string offset 'first_name' Googling this it seems a common problem that appeared in PHP 5.4. I am using 5.5.8
I have modified answer, replace your code with code that posted below 'Modified' text!
I see where you are going with this... but it is not as simplistic as using implode() as Vinie suggested so I am accepting his answer.
0

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

1 Comment

What am I missing? I actually had tried something similar to this, and mine as well as yours produces the same error. A PHP Error was encountered Severity: Notice Message: Array to string conversion Filename: bfmysqli/bfmysqli_driver.php Line Number: 509 A Database Error Occurred Error Number: 1054 Unknown column 'Array' in 'field list' INSERT INTO customers (first_name, last_name, phone) VALUES ('franky', 'smith', Array)
0

mysql doesn’t has any array data type. So we can not store array directly into mysql database. To do this we have to first convert array into string using php serialize() function then save it into mysql database.

for eg:php code to store array in database

$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));

To retrieve array from database

$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
 mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
 $array= unserialize($rs['column']);
 print_r($array);
}

1 Comment

Thanks for this, but as Bugfixer pointed out, your answer is not using Codeinigiter, which is where I am having my problem. I can already do it in vanilla PHP.
0

for array insertion to database use this programme in codeigniter controller=>

$inputdata=$this->input->post();

$phone=array($inputdata['phone']);
       
       foreach($phone as $arr)
       {
           $phoneNo=$arr;

           $f=count($phoneNo);
           
           for($i=0;$i<$f;$i++)
           {
              $arre=[
                  'phone'=>$phoneNo[$i],
                     ]; 
                  
              $insertB= $this->user_model->userdata($arre);      
           }
       }

Comments

-1
public function add_theme_pages(){
        $page_name = $this->input->post('page');
        $page_img = $this->input->post('page_img');

        for($i=0; $i < count($page_name); $i++){

            $pages_data = array(
                    'theme_id' => $this->input->post('theme_id'),
                    'theme_page_name' => $page_name[$i],
                    'theme_page_img' => $page_img[$i]
            );

            if($this->backendM->add_theme_pages($pages_data)){
                $this->session->set_flashdata('message', 'Theme Added Successfully !');
                $this->session->set_flashdata('message_class', 'green');
                $this->create_template();
            }else{
                $this->create_template();
            }
        }   

    }

1 Comment

While your code may provide the answer to the question, please add context around it so others will have some idea what it does and why it is there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.