2016-02-17 20 views
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"]]; 

任何幫助你可以提供的是非常感謝。

回答

1

你需要改變你的插入語句:

$query = "INSERT INTO answers VALUES ('',now(),'".$row['q_eng']."','" . $answer . "')"; 

對不起,我剛纔看到你沒有在你的代碼<form>標籤。是否填充了$_POST

+0

對不起,我在我的代碼中有一個

,我只是試圖發佈我認爲相關的部分。自從我的INSERT檢查$ _POST是否被填充確實可以工作並插入數據後,必須在post中有一些東西。這個問題更可能是因爲現在在數據庫中以「0」保存,所以$ answer不會更新$ _post值。 – Morten

+0

我還建議您使用問題ID來標識問題而不是問題本身。這可能會有問題 – Fuujin

相關問題