Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用MySQL和PHP随机显示10个问题和答案_Php_Mysql_Arrays - Fatal编程技术网

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

使用MySQL和PHP随机显示10个问题和答案,php,mysql,arrays,Php,Mysql,Arrays,我正在用PHP和MySQL做一个调查。我不知道用什么方法来显示一组随机的10个问题及其答案。每个问题可以有2到5个答案 以下是数据库的设置方式: questions: ID | quID | question answers: ID | an_quID | anID | answer 一英镑和一英镑把桌子连在一起 如果我做了以下不准确的代码;为简洁而编辑。我最后做了20次数据库调用 $sql = "SELECT * FROM questions ORDER BY RAND() LIMIT 1

我正在用PHP和MySQL做一个调查。我不知道用什么方法来显示一组随机的10个问题及其答案。每个问题可以有2到5个答案

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

questions:
ID | quID | question

answers:
ID | an_quID | anID | answer
一英镑和一英镑把桌子连在一起

如果我做了以下不准确的代码;为简洁而编辑。我最后做了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个问题及其答案的理想方式是什么

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

然后在代码中,您可以根据返回的行过滤结果,返回的行具有相同的quID,而不是每个问题调用一次来提取答案,您可以提取所有问题ID,并使用MySQL中的in语法一次提取所有答案。然后循环遍历以按您认为合适的方式展平数据

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

您不需要那么多id,每个表一个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>

这不是一个现成的脚本,但它应该可以帮助您解决您遇到的问题。我会这样做:

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

正如Kuchen提到的,您需要对DB进行一些规范化。你不应该使用id,问题id应该是你所需要的全部

我相信它只会返回10个随机答案和它们各自的问题。如果一个问题可以有多个答案,你想显示与该问题相关的所有答案,还是一个特定的答案?MySQL不支持子查询中的限制@konforce:谢谢你在子查询中提供了关于限制的提示。看起来解决的办法是使用for循环将计数改为10来代替限制。可能是这样的:从答案中选择*,从问题中选择,@i:=@i+1