从数据库中检索多个问题和答案,然后将答案重新插入

时间:2016-08-25 15:25:27

标签: php database loops

我正在尝试创建一个包含多个问题的民意调查,这些问题都有多个选项作为答案。问题和选项都存储在数据库中。它们位于单独的表中,并在第三个表中连接,描述了它们之间的关系,比如哪些选项属于哪些问题。

现在,我正在向数据库发送查询,该数据库使用此问题的选项检索单个问题。此数据放在一个表单中,其中包含一个提交按钮和一个附加的操作文件。单击提交按钮时,答案将正确存储在数据库中。

当我更改$ _SESSION ['id']时,带有该ID的问题会正确显示该问题的选项。

我的问题是我不知道如何让它显示多个问题及其选项。要么所有问题都应该在一个页面上显示,或者您应该能够在回答一个问题后单击“下一步”。我一直试图将它全部放入for循环但没有成功。

我的index.php看起来像这样

   <?php
   session_start();
   $_SESSION['id'] = 1;

    include('dbconfig.php');

        $query = "SELECT * 
        FROM question
        INNER JOIN question_options
        ON question.question_id = question_options.question_id
        INNER JOIN options
        ON options.options_id = question_options.options_id
        WHERE question_options.question_id = ".$_SESSION['id'];
        $result_question = mysqli_query($dbc,$query);
        $row = mysqli_fetch_array($result_question);

        echo $row['question_text'];
?>

<br>

<form id="form" method="post" name="formsub" action="answers.php" enctype="multipart/form-data">

<?php

$qry = "SELECT * 
        FROM question
        INNER JOIN question_options
        ON question.question_id = question_options.question_id
        INNER JOIN options
        ON options.options_id = question_options.options_id
        WHERE question_options.question_id = ".$_SESSION['id'];
        $results = mysqli_query($dbc,$qry);

   while($row = mysqli_fetch_array($results)): ?>
      <!-- Echo out values {id} and {name}   -->
      <input type="radio" name="options" value="<?php echo $row['options_id']; ?> "><?php echo $row['options_text'] . '<br />'; ?>
    <?php endwhile; ?>

<input type="submit" name="Submit" value="Næste" id="submitBtn" class="btn btn-default"/>
</form>

动作文件如下所示

<?php 
session_start();
    include('dbconfig.php');

    $options = $_POST['options'];

$query = "INSERT INTO answer (answer_id, question_id, options_id) VALUES ('NULL', '".$_SESSION['id']."', '".$options."')";
mysqli_query($dbc,$query);

?>

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

// fetch questions from db
$questionsSql = "SELECT * FROM question"; // add your WHERE conditions
$questions = $dbc->query($questionsSql)->fetch_all(MYSQLI_ASSOC);

// create comma separated string with question ids
$questionIds = array_column($questions, 'question_id');
$questionIdsString = implode(',', $questionIds);

// fetch related options from db
$optionsSql = "
    SELECT o.*, qo.question_id
    FROM options o
    INNER JOIN question_options qo
    ON qo.option_Id = o.option_id
    WHERE qo.question_id IN ({$questionIdsString})
";
$options = $dbc->query($optionsSql)->fetch_all(MYSQLI_ASSOC);

// assign options to questions
foreach ($options as $option) {
    $question['options'][] = $option;
}

现在您有一个带有问题和相关选项的嵌套数组结构。您将需要嵌套循环来呈现表单:

foreach ($questions as $question) {
    // print question
    foreach ($question['options'] as $option) {
        // print radio button for the option
    }
}