php - 如何在数据库中插入正确的值

标签 php javascript jquery sql mysqli

<分区>

我这里有一个 jsfiddle:http://jsfiddle.net/ybZvv/58/

请按照 fiddle 中的步骤操作:

1: 当你打开 fiddle 时,点击“添加问题”按钮两次,这将追加 2 行。

2:在第一行选择答案按钮“A”和“C”,在第二行选择答案按钮“A”、“B”和“E”。每个所选答案按钮的文本输入值显示在下方。

现在我要做的是将问题编号和答案值发布到数据库中。

发布时数据库应该如下所示:

问题表:

QuestionId (Question Number)
1
2

答案表:

AnswerId (auto)  QuestionId  Answer
1                1           A
2                1           C
3                2           A
4                2           B
5                2           E

我的问题是,如何在下面的 mysqli 代码中发布答案和正确的问题编号,以便它在“问题”和“答案”表中插入这些答案和问题编号?

下面我已经设置了 mysqli/php 代码,但它需要重新调整以便它可以正确插入答案和相关问题编号。

$i = 0;
$c = count($_POST['numQuestion']); //count number of rows

for($i = 0;  $i < $c; $i++ ){

$questionsql = "INSERT INTO Question (QuestionId) 
    VALUES (?)";


    if (!$insert = $mysqli->prepare($questionsql)) {
      // Handle errors with prepare operation here
    }

$insert->bind_param("i", $_POST['numQuestion'][$i]);

        $insert->execute();

        if ($insert->errno) {
          // Handle query error here
        }

        $insert->close();

        $lastID = $mysqli->insert_id;

         $answersql = "INSERT INTO Answer (QuestionId, Answer) 
    VALUES (?, ?, ?)";

      if (!$insertanswer = $mysqli->prepare($answersql)) {
      // Handle errors with prepare operation here
    }  


    $insertanswer->bind_param("is", $lastID, $_POST['value'][$i]);

        $insertanswer->execute();

        if ($insertanswer->errno) {
          // Handle query error here
        }

        $insertanswer->close();

}

我已经为上述场景做了一个 var_dump($_POST),这是它的输出:

array(2) { 
            ["numQuestion"]=> array(2) { 
                                        [0]=> string(1) "1" 
                                        [1]=> string(1) "2" 
                                       }
           ["submitDetails"]=> string(14) "Submit Details" 
           ["value"]=> array(4) { 
                                    ["answerARow"]=> string(1) "A" 
                                    ["answerCRow"]=> string(1) "C" 
                                    ["answerBRow"]=> string(1) "B" 
                                    ["answerERow"]=> string(1) "E" 
                                } 
        }

我收到 2 个相同的错误:

Warning: mysqli_stmt::execute(): (23000/1048): Column 'Answer' cannot be null in /.../ on line 257 Warning: mysqli_stmt::execute(): (23000/1048): Column 'Answer' cannot be null in /.../ on line 257

更新:

我已经更新了 fiddle 以包含多维数组,抱歉我忘了把它放进去,但是代码行如下:

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

我的建议是使用以下格式的多维数组:value[n][],其中 n 是问题编号。使用这个新设置,您应该最终得到以下输入字段:

<input type="hidden" value="A" name="value[1][]">
<input type="hidden" value="B" name="value[1][]">
<input type="hidden" value="A" name="value[2][]">
<input type="hidden" value="C" name="value[2][]">
<input type="hidden" value="E" name="value[2][]">

请注意,所选值在值属性中进行了编码。 name 属性只包含值所属的问题。

最佳答案

$POST 似乎没有所有信息,我建议您更改帖子结构以将问题与答案联系起来,如下所示:

array(2) { 
            ["numQuestion"]=> array(2) { 
                                        [0]=> string(1) "1" 
                                        [1]=> string(1) "2" 
                                       }
           ["submitDetails"]=> string(14) "Submit Details" 
           ["question_1"] => array(2) {
                                        [0] => string(1) "A"
                                        [1] => string(1) "C"
                                      }
           ["question_2"] => array(2) {
                                        [0] => string(1) "A"
                                        [1] => string(1) "B"
                                        [2] => string(1) "E"
                                      }
        }

现在,如果帖子有那个结构,你可以做这样的事情来插入数据:

$numQuestionArray = $_POST["numQuestion"];

for($i =0; $i < count($numQuestionArray);$i++)
{
    $questionId = $numQuestionArray[$i];

    $questionsql = "INSERT INTO Question (QuestionId) VALUES (?)";

    if (!$insert = $mysqli->prepare($questionsql)) {
      // Handle errors with prepare operation here
    }

    $insert->bind_param("i", $questionId);

    $insert->execute();

    if ($insert->errno) {
      // Handle query error here
    }

    $insert->close();

    $lastID = $mysqli->insert_id;

    $questionAnswerPostStr = "question_".$questionId;

    $answerArray = $_POST[$questionAnswerPostStr];

    for($j =0; $j < count($numQuestionArray);$j++)
    {
        $answer = $numQuestionArray[$j];

        $answersql = "INSERT INTO Answer (QuestionId, Answer) VALUES (?, ?)";

        if (!$insertanswer = $mysqli->prepare($answersql)) {
          // Handle errors with prepare operation here
        }  

        $insertanswer->bind_param("is", $lastID, $answer);

        $insertanswer->execute();

        if ($insertanswer->errno) {
          // Handle query error here
        }

        $insertanswer->close();
    }
}

但是,我仍然认为 question_id 应该在表中自动递增,而不是插入 $POST 值。

关于php - 如何在数据库中插入正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12849010/

相关文章:

java - 从 PHP 生成和解码二维码

javascript - FrameId 未定义

javascript - 将不同的 JavaScript 对象合并到一个对象中

javascript - 使用 HTML 将文件上传到 Node.js

javascript - 获取父元素以外的元素的偏移量?

javascript - 如何让滚动条停留在底部?

jquery - 为什么此代码会将表单输入发送到 URL?

php - php 中的 new DateTime() 与 new DateTime ('NOW' )

php - 使用 sha256_password(访问被拒绝)时如何使用 PHP 的 mysqli 连接到 MySQL

php - 后端的 magento 中缺少图像上传按钮