I am inserting values into a “Question” and “Answer” Table. Now the Question Table is fine as that if I insert 2 questions then the table it displays is below:
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
But the “Answer” Table is causing the problem, it duplicates the answers when it inserts, the table currently looks like below:
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
The table should look like below:
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
Why is it duplicating answers?
Below is the php and mysqli code:
<?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();
}
?>
The var_dump($_POST) shows this below:
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"
}
}
}
You have a loop nesting problem. The for, if I get it right, is running the questions and the foreach the answers. The problem is that they should be indipendent from each other. In your code, instead, the foreach is run at every question causing the answers to be inserted twice.
This should work: