PHP表单添加新的数据库行

时间:2019-02-18 20:02:42

标签: php

我有以下代码:

我向数据库“ titlu”添加了新行,但是当我提交表单时,该行什么也没有。我很困惑。有人可以向我解释哪里有问题吗?

if(isset($_POST['submit'])) {
    // Get POST variables, assing to regular variables
    $question_number    = $_POST['question_number'];
   $question_text = $_POST['question_text'];
    $correct_choice     = $_POST['correct_choice'];
    // choices array
    $choices = [];
    $choices[1] = $_POST['choice1'];
    $choices[2] = $_POST['choice2'];
    $choices[3] = $_POST['choice3'];
    $choices[1] = $_POST['titlu1'];
    $choices[2] = $_POST['titlu2'];
    $choices[3] = $_POST['titlu3'];


    // Insert question
    $query = "INSERT INTO `questions` (question_number, question) VALUES('$question_number','$question')";

    $insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);

    if($insert_row){
        foreach($choices as $choice => $value)
		{
           if($value != ''){
               if($correct_choice == $choice) {
                   $is_correct = 1;
               } else {
                   $is_correct = 0;
               }
               $query = "INSERT INTO `choices`(question_number, is_correct, choice, titlu)VALUES('$question_number', '$is_correct', '$value', '$value')";

               $insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);

               if($insert_row) {
                   continue;
               } else {
                   die('Error : ('.$mysqli->errno.') ' . $mysqli->error);
               }
           } 
        }
        $msg = "Questions has been added";
    }
}

我认为这是问题所在

if($insert_row){
    foreach($choices as $choice => $value)

1 个答案:

答案 0 :(得分:2)

当您INSERT INTO questions插入的是未定义变量$question的值时,而不是我认为您尝试插入的$question_text

您的查询应如下所示。

INSERT INTO `questions` (question_number, question) VALUES('$question_number','$question_text')

编辑:

也许您要设置$choices,以便将每个值的键设置为“ titlu”

$choices[$_POST['titlu1']] = $_POST['choice1'];
...

然后您可以将第二个查询设置为

INSERT INTO `choices`(question_number, is_correct, choice, titlu) VALUES('$question_number', '$is_correct', '$value', '$choice')

或类似的东西。