从MYSQL数据库中随机输出行项

时间:2013-04-19 11:39:37

标签: php mysql facebook

我有一个包含以下字段和示例的数据库表:

QuestionID
Question
AnswerA
AnswerB
AnswerC
AnswerD
CorrectAnswer

示例:

QuestionID: 1
Question: What is 2 + 2?
AnswerA: 1
AnswerB: 2
AnswerC: 3
AnswerD: 4
CorrectAnswer: 4

如果我的数据库有20个问题,我怎么才能得到它,这样不仅问题以随机顺序出现,而且答案出现在不同的单选按钮上(以防止用户记住正确答案的位置) 。这将被集成到Facebook应用程序中。下面是我的SQL查询:

$sql="SELECT DISTINCT Question, QuestionID, AnswerA, AnswerB, AnswerC, AnswerD FROM miniproj ORDER BY rand() LIMIT 1";

这是我正在使用的while语句(我理解mysql_fetch_array已被弃用但我可以再次排序):

while ($myrow = mysql_fetch_array($result))
        {
            $answers = array($myrow['AnswerA'], $myrow['AnswerB'], $myrow['AnswerC'], $myrow['AnswerD']);
            shuffle($answers);
            echo("<form action='question.php' method='POST'>\n");
            echo("<h1>");
            echo("Q: ");
            echo($myrow['Question']);
            echo("</h1>");
            echo("<input type='radio' name='comments' value='A'>\n");
            echo($myrow['AnswerA']);
            echo("<p>");
            echo("<input type='radio' name='comments' value='B'>\n");
            echo($myrow['AnswerB']);
            echo("<p>");
            echo("<input type='radio' name='comments' value='C'>\n");
            echo($myrow['AnswerC']);
            echo("<p>");
            echo("<input type='radio' name='comments' value='D'>\n");
            echo($myrow['AnswerD']);
            echo("<p>");
            echo("<br />");
            echo("<input type='submit' value='Submit'>\n");
            echo("</form>\n");
        }

任何提示都会很棒

1 个答案:

答案 0 :(得分:1)

你需要在PHP脚本的开头添加以下函数(感谢 Jon Stirling `s solution):

<?php
function shuffle_keys(&$array){
    $keys = array_keys($array);

    shuffle($keys);

    $result = array();

    foreach($keys as $key){ $result[$key] = $array[$key]; }

    $array = $result;
}
?>

然后,当你处理结果集时,我建议你这样做:

<?php
while($myrow = mysql_fetch_array($result))
    {
        $answers = array(
            'A' => $myrow['AnswerA'],
            'B' => $myrow['AnswerB'],
            'C' => $myrow['AnswerC'],
            'D' => $myrow['AnswerD']
        );

        shuffle_keys($answers);

        echo "<form action='question.php' method='POST'>",
             PHP_EOL,
             "<h1>Q: {$myrow['Question']}</h1>";

        foreach($answers as $key => $value){
            echo "<p><input type='radio' name='comments' value='{$key}'>{$value}</p>";
        }

        echo "<input type='submit' value='Submit'>",
             PHP_EOL,
             "</form>",
             PHP_EOL;
    }
?>

P.S。: This topic建议您避免使用*** mysql _ ****函数。这是旧的和不推荐的扩展。请改用*** mysqli _ ****或*** PDO _ ****。