Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple text inputs with same name - add to database

I have a form with several fields, all of which can be multiplied

<input type="text" name="child_name[]" />
<input type="text" name="child_age[]" />
<input type="text" name="child_gender[]" />    
<input type="text" name="child_school[]" />

I want to add multiple rows to a table in the database using a foreach, but every time I try I get an error saying

"Unknown column 'Array' in 'field list'"

When i print out the data it shows all of the fields as arrays, so I must be doing something wrong with the foreach statement, but I have no idea what

Array ( [child_name] => Array ( [0] => child one [1] => child two) [child_age] => Array ( [0] => 14 [1] => 13 ) [child_gender] => Array ( [0] => male [1] => female ) [child_school] => Array ( [0] => burnside [1] => summer heights high ) )

Any help would be greatly appreciated!#

UPDATED

Here is the code for my foreach

foreach ($_POST['child_name'] as $child_name)
    {
        $insert_children_data = array(
            'child_name' => $_POST['child_name'],
            'child_age' => $_POST['child_age'],
            'child_gender' => $_POST['child_gender'],
            'child_school' => $_POST['child_school']
        );
        $insert = $this->db->insert('portrait_children', $insert_children_data);
        return $insert;
    }
like image 871
Pooshonk Avatar asked Aug 26 '26 07:08

Pooshonk


1 Answers

Try this (assuming your form got same number of elements for each of the child_name, child_age etc):

for ($ix=0; $ix<count($_POST['child_name']); $ix++)
{
    $insert_children_data = array(
        'child_name' => $_POST['child_name'][$ix],
        'child_age' => $_POST['child_age'][$ix],
        'child_gender' => $_POST['child_gender'][$ix],
        'child_school' => $_POST['child_school'][$ix]
    );

    $insert = $this->db->insert('portrait_children', $insert_children_data);
    //return $insert; //you cant return here. must let the loop complete.
}
like image 146
Raheel Hasan Avatar answered Aug 28 '26 21:08

Raheel Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!