Problem with nested foreach loop

I have foreach loop within a foreach loop, but when I insert into the db, it inserts more than 1 entry for the each item… Is my foreach loop wrong for what I am trying to do.


<input type="hidden" name="question_id[]" value="<?php echo $j->id;?>"/>

<input name="answers[]" id="questions" class="deal_form"/>


		$answers = $this->input->post('answers');
			$question_id = $this->input->post('question_id');
				foreach($answers as $d) {
					foreach($question_id as $q){


		function insert_survey_answers($answer,$id){
			$query = "INSERT INTO survey_answers (answer,question_id) VALUES(".$this->db->escape($answer).",'".$id."')";

Something tells me you dont want nested foreach loops, you just want to do

            foreach($answers as $key =&gt; $d) {

To be very blunt yes it is as you as simple loop through one array then through another until your completely finishing running through the answers array, the below code however should fix the problem.

foreach ($question_id as $key => $question) {
    $this->model_survey->insert_survey_answers($answers[$key], $question);
Off Topic:

StarLion beat me to it but we both had the same idea

It may be worth re-structuring/renaming your input fields.

You can use

<input type="text" name="Answer[1]" value="Answer value" />

the number within [1] will contain the question id, allowing you to get both the QuestionID and the Answer to insert into the database in one foreach, rather than doing multiple foreach’s etc.


What I think you’re trying to do, and what I think people are trying to say is you’ve got a hidden input for NOTHING.

<input name=“answers[‘,$j->id,’]” id=“questions” class=“deal_form”/>

That’s it, just one input. (note I’d put that in an echo and lose the stupid open/close on every line – but I’m the nut that wants to see <?php and ?> removed from PHP entirely.)

Then it’s just a simple:

$answers = $this->input->post('answers');
foreach($answers as $key => $data) {

Honestly though – it looks to me like you’re taking something simple and making it needlessly complex; making copies of elements and throwing objects around elements for no good reason.