使用MySQL和PHP显示一组随机的10个问题和答案

时间:2010-06-26 00:06:51

标签: php mysql arrays

我正在使用PHP和MySQL进行调查。我无法弄清楚用什么方法来显示随机的10个问题及其答案。每个问题可以有2到5个答案。

以下是数据库的设置方法:

questions:
ID | quID | question

answers:
ID | an_quID | anID | answer

quID和an_quID将表链接在一起。

如果我执行以下操作(不是确切的代码;为简洁起见而编辑)。我最终做了20次数据库调用。

$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的问题在于,据我所知,你不能在你指定密钥的地方建立关联数组。

显示随机的10个问题及其答案的理想方法是什么?

4 个答案:

答案 0 :(得分:1)

而不是每个问题1次调用以获取答案,您可以将所有问题ID拉出来并使用MySQL中的IN()语法立即获取所有答案。然后循环以根据需要展平数据

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

答案 1 :(得分:1)

joshtonic非常接近。我会做这样的事情:

SELECT * FROM answers WHERE an_quID IN (SELECT quID FROM questions ORDER BY RAND() LIMIT 10);

正如Kuchen所说,您需要对数据库进行一些规范化。你不应该使用id和question_id(id应该是你所需要的全部);

答案 2 :(得分:0)

这样的事情:

SELECT * FROM questions AS q INNER JOIN answers AS a ON q.quID = a.an_quID 
ORDER BY RAND() LIMIT 10

然后在您的代码中,您可以根据使用相同 quID

返回的行来过滤结果

答案 3 :(得分:0)

您不需要那么多ID,每个表一个,并且可以有很多问题的答案,所以我们需要一个非唯一字段,在答案中指向问题ID:

questions: 
id | question

answers:
id | id_questions | answer | correct

循环中的数据库查询(99%的时间)都是坏事 获取问题,并使用WHERE IN和问题ID来获取所需的条目。

基本的工作示例:     

/** Tables

    CREATE TABLE `questions` (
      `id` INT  NOT NULL AUTO_INCREMENT,
      `question` VARCHAR(255)  NOT NULL,
      PRIMARY KEY (`id`)
    )
    ENGINE = MyISAM;

    CREATE TABLE `test`.`answers` (
      `id` INT  NOT NULL AUTO_INCREMENT,
      `id_questions` INT  NOT NULL,
      `answer` VARCHAR(255)  NOT NULL,
      `correct` BOOL  NOT NULL,
      PRIMARY KEY (`id`)
    )
    ENGINE = MyISAM;

 */

/** Test Data

    INSERT INTO `questions` (id,question) VALUES
    (null,'Pick A!'),(null,'Pick B!'),(null,'Pick C!'),(null,'Pick D!');

    INSERT INTO `answers` (id,id_questions,answer,correct) VALUES
    (null,1,'Answer A',1),(null,1,'Answer B',0),(null,1,'Answer C',0),(null,1,'Answer D',0),
    (null,2,'Answer A',0),(null,2,'Answer B',1),(null,2,'Answer C',0),(null,2,'Answer D',0),
    (null,3,'Answer A',0),(null,3,'Answer B',0),(null,3,'Answer C',1),(null,3,'Answer D',0),
    (null,4,'Answer A',0),(null,4,'Answer B',0),(null,4,'Answer C',0),(null,4,'Answer D',1);

 */

define('NUM_OF_QUESTIONS_TO_DISPLAY',3);

// DB login data
$db_login = array('host' => 'localhost',
                  'user' => 'test',
                  'pass' => 'tset',
                  'base' => 'test'
                 );

// DB connect
$db = new mysqli($db_login['host'],$db_login['user'],$db_login['pass'],$db_login['base']);

if (mysqli_connect_errno()) 
    trigger_error('DB connection failed: '.mysqli_connect_errno());


// Get questions
if ($res = $db->query('SELECT q.id, q.question FROM questions q 
                       ORDER BY RAND() LIMIT '.(int)NUM_OF_QUESTIONS_TO_DISPLAY.';')) {
    $questions = array();
    $questions_ids = array();
    while ($r = $res->fetch_assoc()) {
        $questions[] = $r;
        $questions_ids[] = $r['id'];
    }
}

// Get the answers
if ($res = $db->query('SELECT a.id_questions, a.answer, a.correct FROM answers a 
                       WHERE (a.id_questions IN ('.implode(',',$questions_ids).')) 
                       ORDER BY RAND();')) {
    $answers = array();

    while ($r = $res->fetch_assoc())
        $answers[$r['id_questions']][] = $r;
}

?>
<html>
    <head>
        <title>Foo!</title>
    </head>
    <body style="margin: 100px;">
        <?php foreach ($questions as $question) : ?>
            <strong><?php echo $question['question']; ?></strong>
            <small>(Question id:<?php echo $question['id']; ?>)</small>
            <ul>
                <?php foreach ($answers[$question['id']] as $answer) : ?>
                    <li><?php echo $answer['answer'].($answer['correct'] ? '(*)' : ''); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endforeach; ?>
    </body>
</html>

(不是一个随时可用的脚本,但它可以帮助你解决你遇到的问题)