试图通过测验系统获得良好的订单

时间:2013-01-22 13:38:35

标签: php html mysql phpmyadmin while-loop

我正在尝试制作一个测验系统,但它会输出:

Question1
Answer1
Question1
Answer2

等等......而不是

Question1
Answer1
Answer2
... and so on

我该如何解决?

代码:

$question = mysql_query("SELECT questions.*, answers.* FROM questions inner join answers on questions.id=answers.question_id");

while($row = mysql_fetch_assoc($question))
{
    echo $row['question'].'<br />' .$row['answer'].'<br />';            
}

2 个答案:

答案 0 :(得分:3)

修复你的WHILE LOOP。它将始终打印问题和答案。快速修复看起来像这样:

$previousQuestion = null;
while($row = mysql_fetch_assoc($question))
{
    if($row['question'] !== $previousQuestion) {
        echo $row['question'].'<br />';
    }

    echo $row['answer'].'<br />';

    $previousQuestion = $row['question'];
}

语法可以通过其他方式简化,但这将有效。基本上,由于问题及其答案之间存在一对多的关系,因此只有在与上一行的问题不同时才打印问题。

答案 1 :(得分:0)

如果你只想在MySQL中这样做,你可以这样做:

SELECT question AS 'Question And Its Answers'
FROM
(
  SELECT 0 AS Type, id, question FROM questions 
  UNION ALL
  SELECT 1, question_id, answer FROM answers 
) t
ORDER BY id, Type;

SQL Fiddle Demo

这会给你:

| QUESTION AND ITS ANSWERS |
----------------------------
|                question1 |
|                      eee |
|                       dd |
|                      dsd |
|                question2 |
|                       df |
|                       fd |
|                question3 |
|                      ans |
|                       dd |
|                       ad |