通过PHP将HTML表单数据插入mySQL(表单数组因表行数而异)


Insert HTML form data to mySQL via PHP (form array vary from amount of table rows)

我有一个HTML表单,用户可以在其中选中多达50个不同的问题。他们必须勾选最少1个问题,最多50个问题

在他们提交表单后,我需要将数据(form_array)插入到我的mySQL表中问题。该表包含50个问题行(参见下面的问题表示例)。

我知道INSERT INTO 'questions' (question1, question2, question3, question4,....question50) VALUES (value1, value2, value3...),但我面临的挑战是,由于表格中检查的问题(值)的数量可能会有所不同,我不知道如何将form_array插入我的问题表中。

问题form_array中插入为truefalse,具体取决于它们是否以html形式标记。

问题表除了50个问题外,还有一个自动递增的主ID和2个外键。

我欢迎所有关于如何使用上述场景插入数组的建议/示例?

问题表如下所示:

  `question1` tinyint(1) NOT NULL,
  `question2` tinyint(1) NOT NULL,
  `question3` tinyint(1) NOT NULL,
  `question4` tinyint(1) NOT NULL,
  `question5` tinyint(1) NOT NULL,
  `question6...etc etc...up to 50 questions

我想您想存储50个问题的答案,对吧?

首先,您的表结构应该是这样的:

questions
---------
id: primary key, int(11), auto increments
question/title: varchar(255)
answers
-------
id: primary key, int(11), auto increments
question_id: int(11)
answer: tinyint(1)

这是棘手的部分。显示问题(我使用了mysqli,因为我不知道你在用什么):

$result = $mysqli->query("SELECT * from questions");
while ($question = $result->fetch_assoc()) {
    print 'Question: ' . $question['title'];
    print '<input type="hidden" name="answerswers[]['question_id']" value="' . $question['id'] . '">';
    print '<input type="radio" name="answerswers[]['answer']" value="1"> Yes'; 
    print '<input type="radio" name="answerswers[]['answer']" value="0"> No';
}

现在,当用户提交他的答案时:

if(isset($_POST['submit'])) {
    $answers = $_POST['answers'];
    if(count($answers) > 1) {
        //Loop through all the answers
        foreach($answers as $answer) {
            $mysqli->query("INSERTO INTO answer ('question_id', 'answer') VALUES ('{$answer['question_id']}', '{$answer['answer']')"); //Insert the answers one by one
        }
    } else {
       print 'You need to submit at least one answer!'
    }
}

我还没有测试代码。这仍然是非常基本的,但我认为这正是你所需要的…:-)。