簡體   English   中英

通過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插入我的問題表。

根據是在html表單中標記問題還是未標記問題 ,將問題truefalse插入到form_array

除了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="answers[]['question_id']" value="' . $question['id'] . '">';
    print '<input type="radio" name="answers[]['answer']" value="1"> Yes'; 
    print '<input type="radio" name="answers[]['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!'
    }

}

我還沒有測試代碼。 這仍然是非常基本的,但是我認為這正是您所需要的... :-)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM