PHP - 使用数据库值定义数组

时间:2016-06-09 21:47:44

标签: php arrays mysqli

我的任务是制作一个网络应用程序,要求用户提供特定问题的答案(选项) - 根据所选的选项执行不同的操作。每个问题都存储在数据库中,以及每个问题的7个选项。例如,"你年轻时最喜欢的食物是什么?"可以有选择:饼干,蛋糕,馅饼等。

我实际上设法编写脚本来使用mysqli_fetch_array使用1D和2D索引数组来定义每个值。但是,当我尝试使用for循环查看存储在每个问题和答案数组中的数据时,我遇到了一个奇怪的问题......显示了所有问题,但只显示了第一个问题的答案。

这是我的代码:

<?php
    session_start();
    $con = mysqli_connect("server","username","password","db");

    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }


    $arr = array();
    $ans = array();
    $i = 0;
    $c = 0;
    $q_sql = "SELECT Question FROM Question";

    $question = mysqli_query($con,$q_sql);

    while($q = mysqli_fetch_array($question)){
        $arr[$i] = $q['Question'];

        $a_sql = "SELECT Answer FROM Answer WHERE QuestionID = ".($i+1);
        $answer = mysqli_query($con,$a_sql);

        while($a = mysqli_fetch_array($answer)){
            $ans[$i][$c] = $a['Answer']; // array(0 => $i, 1 => $a);
            $c++;
        }
        $i++;
    }

    mysqli_close($con);
?>

HTML:

<!DOCTYPE html>

<html>
    <head>
        <title></title>
    </head>
    <body>
    <?php

        for ($i=0; $i < sizeof($arr); $i++){
            print "<br/>".$arr[$i];
            for ($c=0; $c < sizeof($ans[$i]); $c++){
                print "<br/>".$ans[2][$c];          
            }
        }

    ?>
    </body>
</html>

如果需要更多信息,请询问。我不知道为什么只显示一组答案,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

假设每个问题有5个答案。在Question查询的第一次迭代期间,$i = 0$c0运行到4。在第二次迭代期间,$i = 1$c59,因此您填写了$ans[1][5]。但是,打印答案的循环期望第二个索引始终从0运行到sizeof($ans[$i])-1

您需要在内循环之前将$c重置为0,而不是在外循环之前。

但是也没有理由使用多个查询和嵌套循环,您应该将它们连接到一个查询中。

$sql = "SELECT q.ID, Question, Answer
        FROM Question AS q
        LEFT JOIN Answer AS a ON a.QuestionID = q.ID
        ORDER BY q.ID";
$result = mysqli_query($con, $sql);
$last_qid = null;
$i = -1;
while ($row = mysqli_fetch_assoc($result)) {
    if ($row['ID'] != $last_qid) {
        $i++;
        $arr[$i] = $row['Question'];
        $ans[$i] = array();
    }
    if ($row['Answer'] !== null) { // skip null value if there were no answers
        $ans[$i][] = $row['Answer'];
    }
}