I am trying to insert each answer for each question in the database. Problem is that there is a possibility that a question may have no answers, so I tried the code below but it does not insert a db row if a question has no answer, what I was trying to do is that if no answer then display the string No Answer under the Answer column for that question:
$answersql = "INSERT INTO Answer (QuestionId, Answer)
VALUES (?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
if( $insert && $insertanswer)
{
$c = count($_POST['numQuestion']);
$question_ids = array();
for($i = 0; $i < $c; $i++ )
{
... //Question INSERT goes here
$questionId = $mysqli->insert_id;
$question_ids[$questionNo] = $questionId;
}
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$quesid = (int)$question_ids[$id];
foreach($value as $answer)
{
if($answer == '' || $answer === null){
$answer = 'No Answer';
}
$insertanswer->bind_param("is", $quesid, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 7;
}
}
}
//close your statements at the end
$insertanswer->close();
}
The ['value'] comes from an input:
var $newBtn = $(("<input class='answerBtnsRow answers' type='button' style='display:%s;' onclick='btnclick(this, " + gQuestionIndex + ");' />").replace('%s', $this.is(':visible') ? 'inline-block' : 'none')).attr('name', "value[" + gQuestionIndex + "][]").attr('value', $this.val()).attr('class', $this.attr('class')).attr('id', $this.attr('id') + 'Row');
UPDATE:
Below is the SHOW CREATE TABLE for the Answer Table:
CREATE TABLE `Answer` (
`AnswerId` int(10) NOT NULL AUTO_INCREMENT,
`QuestionId` int(10) NOT NULL,
`Answer` varchar(10) DEFAULT NULL,
PRIMARY KEY (`AnswerId`)
) ENGINE=InnoDB AUTO_INCREMENT=280 DEFAULT CHARSET=utf8
Below is a var dump where if I set question 1 to have answers B and C and set question 2 to have no answers at all, it outputs the following:
var_dump($question_ids);
var_dump($results);
array(2) {
[1]=> int(247)
[2]=> int(248)
}
array(1) {
[1]=> array(2) {
[0]=> string(1) "B"
[1]=> string(1) "C" }
}
You can tell from your var_dumps that you have two questions, but only one set of answers. your design flaw doesn’t link the answers to the questions, from what I can see.
no second index in $results, means no second set of answers, therefore no insert …
but if you have three questions, and two answer sets, do those answers belong to question 1&2 or 2&3, or 1&3. I am not see how you mach your question id to the result set.