处理一个问题的多个动态答案



我有两个表,一个用于提问,另一个用于回答。每个问题可以有3-5个答案。

问题表:

_________________
| id | question |
|____|__________|
|  1 |    q1    |
|____|__________|

答案表:

__________________________________________
| id | answer | is_correct | question_id |
|____|________|____________|_____________|
|  1 |    a1  |     0      |      1      |
|____|________|____________|_____________|
|  2 |    a2  |     0      |      1      |
|____|________|____________|_____________|
|  3 |    a3  |     1      |      1      |
|____|________|____________|_____________|

在更新页面上,我想更新问题和答案。

更新表格看起来是这样的:

<input type="text" name="question"/>
<input type="text" name="answer-1"/>
<input type="text" name="answer-2"/>
<input type="text" name="answer-3"/>

在提交页面上,我试图获得答案值和它们的id。

我试过了:

foreach($_POST as $input){
if (strpos($input, 'answer-') !== false) {
$answers[] = $input;
}
}

但通过这种方式,我只得到了值,而不是这些答案的id。

我还试图给出所有的答案name="answers[]"。但同样的事情,我也无法得到答案。

使用foreach循环语法,您可以同时访问数组的键和值,如下所示:

foreach($_POST as $inputName => $inputValue) {
if (strpos($inputName, 'answer-') !== false) {
$answers[] = $inputValue;
}
}

我会这样做:

<input type="text" name="answer[1]"/>
<input type="text" name="answer[2]"/>
<input type="text" name="answer[3]"/>

php看起来像这样:

foreach($_POST['answer'] as $id => $answer) {
// do the database instruction
}

最新更新