我将值插入到“问题”和“答案”表中。现在问题表很好,如果我插入 2 个问题,那么它显示的表如下:
SessionId (PK) QuestionId(Pk) QuestionContent
RZC 1 Name 2 things you will find with a computer
RZC 2 Name three things you will find in a toolbox
但是“答案”表导致了问题,它在插入时重复了答案,该表目前如下所示:
AnswerId (auto PK) SessionId QuestionId Answer
1 RZC 1 A
2 RZC 1 C
3 RZC 2 A
4 RZC 2 B
5 RZC 2 E
6 RZC 1 A
7 RZC 1 C
8 RZC 2 A
9 RZC 2 B
10 RZC 2 E
该表应如下所示:
AnswerId (auto PK) SessionId QuestionId Answer
1 RZC 1 A
2 RZC 1 C
3 RZC 2 A
4 RZC 2 B
5 RZC 2 E
为什么重复答案?
下面是php和mysqli代码:
<?php
var_dump($_POST);
// Prepare your statements ahead of time
$questionsql = 'INSERT INTO Question (SessionId, QuestionId, QuestionContent) VALUES (?, ?, ?)';
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$answersql = 'INSERT INTO Answer (SessionId, QuestionId, Answer) VALUES (?, ?, ?)';
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$c = count($_POST['numQuestion']);
for($i = 0; $i < $c; $i++ )
{
$insert->bind_param('sis', $sessid, $_POST['numQuestion'][$i], $_POST['questionText'][$i]);
$insert->execute();
if ($insert->errno)
{
// Handle query error here
echo __LINE__.': '.$insert->error;
break 2;
}
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$lastID = $insert->insert_id;
foreach($value as $answer)
{
$insertanswer->bind_param('sis', $sessid, $lastID, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 3;
}
}
}
}
//close your statements at the end
$insertanswer->close();
$insert->close();
}
?>
var_dump($_POST) 显示如下:
array(4) {
["numQuestion"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "2"
}
["questionText"]=> array(2) {
[0]=> string(20) "What is 2+2 and 3+3?"
[1]=> string(41) "Which three items will you find in a car?"
}
["submitDetails"]=> string(14) "Submit Details"
["value"]=> array(2) {
[1]=> array(2) {
[0]=> string(1) "A"
[1]=> string(1) "C"
}
[2]=> array(3) {
[0]=> string(1) "A"
[1]=> string(1) "B"
[2]=> string(1) "D"
}
}
}