0

我正在尝试为数据库中的每个问题插入每个答案。问题是问题可能没有答案,所以我尝试了下面的代码,但如果问题没有答案,它不会插入数据库行,我想做的是,如果没有答案,则显示该问题列No Answer下的字符串Answer

 $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();

}

来自['value']输入:

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');

更新:

下面是表的 SHOW CREATE TABLE Answer

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

下面是一个 var 转储,如果我将问题 1 设置为有答案B并将C问题 2 设置为根本没有答案,它会输出以下内容:

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" } 
} 
4

1 回答 1

0

您可以从 var_dumps 看出您有两个问题,但只有一组答案。据我所知,您的设计缺陷并未将问题的答案与问题联系起来。

$results 中没有第二个索引,意味着没有第二组答案,因此没有插入...

但是如果您有三个问题和两个答案集,那么这些答案是否属于问题 1&2 或 2&3 或 1&3。我看不到您如何将您的问题 id 设置为结果集。

于 2013-02-04T20:44:09.770 回答