Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用嵌套的foreach循环获取索引的每个值并保存到数据库php_Php_For Loop - Fatal编程技术网

如何使用嵌套的foreach循环获取索引的每个值并保存到数据库php

如何使用嵌套的foreach循环获取索引的每个值并保存到数据库php,php,for-loop,Php,For Loop,我正在做一个在线考试,我想得到考生的答案并保存到数据库中。现在,我的所有问题和考生答案都存储在数组中,使用名为name=question[]的输入类型文本和输入类型复选框name=“checker[questionID]”。这是示例结果 问题ID:数组([0]=>131[1]=>132[2]=>133[3]=>130) 及 答案ID:数组([131]=>330[132]=>336[133]=>339[130]=>328) 现在,我想将该值保存到我的数据库中,如下所示: 以下是我的php代码,它

我正在做一个在线考试,我想得到考生的答案并保存到数据库中。现在,我的所有问题和考生答案都存储在数组中,使用名为name=question[]的输入类型文本和输入类型复选框name=“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')");
 }
}

请帮帮我。谢谢:)

您根本不需要
$\u POST[“question”]
数组。由于您的
$\u 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')");
}

你完成了

您根本不需要
$\u POST[“question”]
数组。由于您的
$\u 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])");
}

在这里,您容易受到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])");
}