构造while语句用于在MySQL数据库中存储动态生成的php表单问题?

时间:2016-02-17 13:15:55

标签: php mysql

我正在进行一项简单的调查,向用户展示一个表格中有许多问题的网站。

问题存储在数据库中而不是“硬编码”,因为将来我希望能够向不同的用户展示不同的问题,甚至可以随机化显示哪些问题。

我的问题数据库结构如下所示:

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 个答案:

答案 0 :(得分:1)

您需要更改插入声明:

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

抱歉,我刚看到您的代码中没有<form>标记。 $_POST是否已填满?