I have 2 tables, one for questions and the other for answers. Each question could have 3-5 answers.
Questions table:
_________________
| id | question |
|____|__________|
| 1 | q1 |
|____|__________|
Answers table:
__________________________________________
| id | answer | is_correct | question_id |
|____|________|____________|_____________|
| 1 | a1 | 0 | 1 |
|____|________|____________|_____________|
| 2 | a2 | 0 | 1 |
|____|________|____________|_____________|
| 3 | a3 | 1 | 1 |
|____|________|____________|_____________|
On update page, I want to update both question and its answers.
The update form looks liek this:
<input type="text" name="question"/>
<input type="text" name="answer-1"/>
<input type="text" name="answer-2"/>
<input type="text" name="answer-3"/>
On page submit I'm trying to get the answers values and their ids.
I tried:
foreach($_POST as $input){
if (strpos($input, 'answer-') !== false) {
$answers[] = $input;
}
}
But this way I'm getting the values only not the ids of these answers.
I also tried to give all the answers name="answers[]"
. But it's the same thing I won't be able to get the answers ids.
CodePudding user response:
With the foreach loop syntax you can access the keys and the values of an array simultaneously, like this:
foreach($_POST as $inputName => $inputValue) {
if (strpos($inputName, 'answer-') !== false) {
$answers[] = $inputValue;
}
}
CodePudding user response:
I will do the form like THIS:
<input type="text" name="answer[1]"/>
<input type="text" name="answer[2]"/>
<input type="text" name="answer[3]"/>
The php would look like this:
foreach($_POST['answer'] as $id => $answer) {
// do the database instruction
}