Welcome Guest, Not a member yet? Register   Sign In
Help: About Nested Foreach
#1

[eluser]Wondering Coder[/eluser]
Hi to everyone,

I have a dynamic fields which are field1, field2 & field3. I am able to save the correct data in field1
but in field2 and field3 I am only able to get the last array input in my forms

This is my controller
Code:
function add()
    {
    $data['mod'] = strtolower(get_class($this));
        foreach($_POST['myfield1'] as $field1)   {
            foreach($_POST['myfield2'] as $field2)        {
                foreach($_POST['myfield3'] as $field3)         {
                    $detail = array(
                            'field1' => $field1,
                            'field2' => $field2,
                            'field3' => $field3
                        );
                }
            }
             $this->welcome_model->save($detail);
        }
        $this->output->enable_profiler(TRUE);
     $this->load->view('welcome_success',$data)
}
The values I entered are 1,2,3 and 4,5,6
When profiler is on this is the result:
Code:
POST DATA  
$_POST['myfield1']    

Array
(
    [0] => 1
    [1] => 4
)

$_POST['myfield2']      

Array
(
    [0] => 2
    [1] => 5
)

$_POST['myfield3']      

Array
(
    [0] => 3
    [1] => 6
)

  DATABASE:  login   QUERIES: 2  
INSERT INTO `profile` (`field1`, `field2`, `field3`) VALUES ('1', '5', '6')
INSERT INTO `profile` (`field2`, `field2`, `field3`) VALUES ('4', '5', '6')

As you can see in my inserted queries the field2 & field3 only inserted the last arrays. I'm sure
my nested foreach is not right but can't seem to correct it. (My mind is rotating @_@)

It should be like this:
Code:
INSERT INTO `profile` (`field1`, `field2`, `field3`) VALUES ('1', '2', '3')
INSERT INTO `profile` (`field2`, `field2`, `field3`) VALUES ('4', '5', '6')
#2

[eluser]Wondering Coder[/eluser]
anyone? @_@
#3

[eluser]Wondering Coder[/eluser]
solved it. Had to used different loop for this one.
#4

[eluser]Bigil Michael[/eluser]
can u post the code




Theme © iAndrew 2016 - Forum software by © MyBB