显示随机的一组10个问题和答案与MySQL和PHP [英] Display a random set of 10 questions and answers with MySQL and PHP

查看:105
本文介绍了显示随机的一组10个问题和答案与MySQL和PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP和MySQL的调查。我无法搞清楚用什么方法来显示随机的一组10个问题,他们的答案。每个问题可以有答案2和5之间。

I'm making a survey with PHP and MySQL. I'm having trouble figuring out what method to use to display a random set of 10 questions, and their answers. Each question can have between 2 and 5 answers.

下面是数据库的设置方式:

Here is how the database is set up:

questions:
ID | quID | question

answers:
ID | an_quID | anID | answer

镑和an_quID表链接起来。

quID and an_quID link the tables together.

如果我做了以下(不准确code;编辑为简洁起见)。我最终会做20数据库调用。

If I do the following (not exact code; edited for brevity). I end up doing 20 database calls.

$sql = "SELECT * FROM questions ORDER BY RAND() LIMIT 10";

while($row = mysql_fetch_array($result)) {

    $quID = $row[quID];

    echo "HTML code here";

    "SELECT * FROM answers WHERE an_quID = '$quID'"

    while($inside_row = mysql_fetch_array($inside_result)) {

        $answer = $inside_row[answer];

        echo "HTML code here";

    }

}

我也用array_push(),只有2数据库调用,所有的结果推入阵列尝试。但随着array_push问题是,据我所知,你不能在您指定的按键使关联数组。

I have also tried using array_push(), with just 2 database calls, to push all the results into arrays. But the problem with array_push is that, as far as I can tell, you can't make associative arrays where you specify the keys.

什么是显示随机的一组10个问题的理想方法,而且他们的答案?

What would be the ideal way to display a random set of 10 questions, and their answers?

推荐答案

,你可以把所有的问题的ID并使用IN()语法在MySQL中拉所有的答案立刻。然后依次通过扁平化的数据,你认为合适

Instead of 1 call per question to pull the answers, you could pull all the question ID's out and use the IN () syntax in MySQL to pull all the answers at once. Then loop through to flatten the data as you see fit

SELECT * FROM answers WHERE an_quID IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

这篇关于显示随机的一组10个问题和答案与MySQL和PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆