0
我正在進行一項簡單的調查,其中用戶在一個表單中帶有一些問題的網站。構建while語句在MySQL數據庫中存儲動態生成的php表單問題?
問題存儲在數據庫中,而不是「硬編碼」,因爲將來我希望能夠向不同的用戶提出不同的問題,甚至隨機地顯示哪些問題。
的問題,我的數據庫結構如下:
table: questions
id q_eng
1 Satisfied?
2 Happy?
3 Sad?
這是我想如何存儲的答案:
table: answers
id timestamp question answer
1 2016-02-17 Satisfied? yes
2 2016-02-17 Happy? yes
3 2016-02-17 Sad? no
4 2016-02-18 Satisfied? no
5 2016-02-18 Happy? no
6 2016-02-18 Sad? yes
我用我的存儲問題來填充我的形式PHP,像這樣:
$sql = "SELECT DISTINCT q_eng FROM questions WHERE id = 1";
$result = $con->query($sql);
$row = mysqli_fetch_array($result);
echo "<div class='header'>". $row['q_eng'] ."</div>";
echo "<div class='questions'>";
echo "<input type='radio' name='". $row['q_eng'] ."' id='satisfied_yes value='yes'>";
echo "<label for='satisfies_yes'><img src='satisfied.png' width='15%'></label>";
echo "<input type='radio' name='". $row['q_eng'] ."' id='satisfied_no' value='no'>";
echo "<label for='satisfied_no'><img src='notsatisfied.png' width='15%'></label>";
echo "</div>";
// code repeating for question 2 and question 3 using id = 2 and id = 3.
我現在遇到的麻煩是構建正確的while循環保存不同的問題和答案。
// checks if form has been submitted
if (!empty($_POST)) {
// fetches distinct questions from database
$sql = "SELECT DISTINCT q_eng FROM questions";
$result = $con->query($sql);
// starts loop for each distinct value to save distinct values
while ($row = mysqli_fetch_array($result)) {
// tries to save the value for each question (yes or no)
// this is not working, maybe due to some syntax error.
// echoing $answer displays nothing.
$answer = $_POST[$row["q_eng"]];
// saves the values. seems to be working fine
$query = "INSERT INTO answers VALUES ('',now(),'".$row['q_eng']."','$answer')";
mysqli_query($con,$query);
}
}
現在,我99%肯定,我的錯誤是在這一行,但我一直沒能制定出是否有一些簡單的語法錯誤,或者我是否試圖做一些事情,這不是要工作?
$answer = $_POST[$row["q_eng"]];
任何幫助你可以提供的是非常感謝。
對不起,我在我的代碼中有一個
我還建議您使用問題ID來標識問題而不是問題本身。這可能會有問題 – Fuujin