我想使用这种格式的多维数组:value[n][],其中 n 是问题编号。使用这个新设置,您最终应该得到以下复选框字段:
<input type="checkbox" value="A" name="value[1][]">
<input type="checkbox" value="B" name="value[1][]">
<input type="checkbox" value="A" name="value[2][]">
<input type="checkbox" value="C" name="value[2][]">
<input type="checkbox" value="E" name="value[2][]">
请注意,所选值在 value 属性中编码。name 属性只包含该值所属的问题。
因此,上述输入说明的是:
question 1: answer: A
question 1: answer: B
question 2: answer: A
question 2: answer: C
question 2: answer: E
我想将这些详细信息插入到下面的“问题”和“答案”数据库表中:
问题表:
SessionId QuestionId
MUL 1
MUL 2
答案表:
AnswerId (auto) SessionId QuestionId Answer
1 MUL 1 A
2 MUL 1 B
3 MUL 2 A
4 MUL 2 C
5 MUL 2 E
现在我尝试编写下面的 mysqli/php 代码将这些值插入数据库,但我收到错误并且在想要实现我想要实现的目标方面失败了。我需要帮助才能在相关表中正确插入正确的值。
以下是 php/mysqli 代码:
var_dump($_POST);
$i = 0;
$c = count($_POST['numQuestion']);
for($i = 0; $i < $c; $i++ ){
/*
switch ($_POST['gridValues'][$i]){
case "3":
$selected_option = "A-C";
break;
case "4":
$selected_option = "A-D";
break;
case "5":
$selected_option = "A-E";
break;
default:
$selected_option = "";
break;
}
*/ needed later on when I insert grid values
$results = $_POST['value'];
foreach($results as $id => $value) {
$answer = $value;
$questionsql = "INSERT INTO Question (SessionId, QuestionId)
VALUES (?, ?)";
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("si", $sessid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$insert->insert_id;
foreach($value as $answer) {
$answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
}
$insertanswer->bind_param("sis" $sessid, $lastID, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
}
$insertanswer->close();
}
}
}
下面的var_dump($_POST)
输出:
array(3) {
["numQuestion"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "2"
}
["submitDetails"]=> string(14) "Submit Details" ["value"]=> array(4) {
["answerARow"]=> string(2) "on"
["answerCRow"]=> string(2) "on"
["answerBRow"]=> string(2) "on" ["answerERow"]=> string(2) "on"
}
}
以下是我收到的错误以及每个错误链接到的代码行:
警告:在第 252 行的 /.../ 中为 foreach() 提供的参数无效
foreach($value as $answer) {
警告:mysqli_stmt::execute(): (23000/1062): 第 242 行 /.../ 中键 'PRIMARY' 的重复条目 'MUL-0'
上面的错误表明没有插入任何问题编号,因为它一直显示为“0”