Ok, so I am building an application, that allows the users to post a question, and add 4 possible answers to that question. I have save the question to the database, get the inserted id and assign that to my answers so I can pull the corresponding answers back for the correct questions, however my foreach loop only fires once, as currently I am only adding 1 question, which means that only 1 answers gets added to the database. How can a rewrite my code so that the question gets saved and then a loop over the answers the correct number of times to add the 4 answers for the question?, My current code is below,
$count = count($questions);
for($i = 0; $i < $count; $i ++) {
if($this->questions_model->insert($questions[$i]))
{
$answers[$i]['questions_question_id'] = $this->db->insert_id();
if(!$this->answers_model->insert($answers[$i])) {
$errors = array("Something has gone wrong please try and submit again");
}
}
else
{
$errors = array("Something has gone wrong please try and submit again");
}
}
Don’t use the normal for loop, too much work for you. Use foreach loops. Nest ones at that.
Try this:
The problem I see here is that if your questions and answers are coming from one big form then how do we know which answers go to which questions? Your best bet here is to only submit one question with multiple answers in the same form. Then the above code will work.
Otherwise you need to embed a way to attach the answers to each question ahead of time. Maybe even embed the array of answers in each question. In which case you can do this…
Nested loops and function calls are your friend. If each loop gets much more complex I would recommend encapsulating parts of it into functions that you can call repetitively.