我正在进行在线考试,我想让考生回答并保存到数据库中。现在,我的所有问题和考生答案都使用名称为name = question []的输入类型文本存储在数组中,输入类型复选框名称=“checker [questionID]”。这是样本结果。
问题ID:数组([0] => 131 [1] => 132 [2] => 133 [3] => 130)
和
答案ID:数组([131] => 330 [132] => 336 [133] => 339 [130] => 328)
这是我的PHP代码,它不工作:
$selected = $_POST["checker"];
$quest_id = $_POST["question"];
foreach ($quest_id as $key => $q_id) {
foreach ($selected as $key => $a_id) {
$get_ans = mysqli_query($connections, "INSERT INTO taker_answer VALUES('','$q_id','$a_id')");
}
}
请帮我。谢谢 :)
你根本不需要$_POST["question"]
阵列。由于您的$_POST["checker"]
将问题ID作为键,因此您只需执行以下操作:
$selected = $_POST["checker"];
foreach ($selected as $key => $a_id) {
$get_ans = mysqli_query($connections, "INSERT INTO taker_answer VALUES('','$key','$a_id')");
}
你完成了
在这里你很容易受到SQLIA的影响,请使用mysqli或PDO的预处理语句。
现在,对于您的代码,我认为您不需要第二个循环。你只需从下面的数组索引中选择答案
$selected = $_POST["checker"];
$quest_id = $_POST["question"];
// here $key hold the value of index (hold the key if it's associated array)
// and you can get corresponding value of selected answer by $selected[$key] as $key keep changing its value inside loop
foreach ($quest_id as $key => $q_id) {
$get_ans = mysqli_query($connections, "INSERT INTO taker_answer VALUES('',$q_id,$selected[$key])");
}