下一个和以前的mysql数据库随机记录

i am working on a computer based test, and am unable to get question from the database randomly with the next button displaying a question that has not been previously displayed earlier and the previous button displaying the previously displayed question. I have this code please can anybody help me out.

$specqtn = mysql_query("SELECT * FROM question_reg 
WHERE courseid = '$id'") or die (mysql_error());    
while ($specqtnrow = mysql_fetch_array($specqtn)){
    $qtnid = $specqtnrow['qtnid']."<br>";
} 
echo "<tr><td>Question</td><td>$qtncontent</td></tr>";
while ($i < $count){
    $sql = mysql_query("SELECT * FROM mdlopt 
    WHERE qtnid = $qtnid ORDER BY RAND()") or die (mysql_error()); 
    while($sqlrow = mysql_fetch_array($sql)){
        $count = mysql_num_rows($sql);
        $optid = $sqlrow['optid'];
        $optval = $sqlrow['optval']."<br>";
        echo "<tr><td></td><td><input name='radiobutton' type='radio'    value='$qtnid'/>$optval</td></tr>";
        $i++;
    }
}
echo "<tr><td></td><td><input name='Previous' type='submit' id='Previous'  value='Previous' />";
echo "<input type='submit' name='Next' value='next'>";
echo "<input type='submit' name='Submit' value='Submit' /></td></tr>";

Hi in your code you are retrieving all the rows from the table. just put limit in your sql query you will get what you are looking for.

Depends on your definition of "next" and "previous". I assume that it is the order of courseid. To get the next row you can write a query like this:

SELECT * FROM question_reg
WHERE courseid > '$id'
ORDER BY courseid ASC
LIMIT 1

And this query to get the previous one:

SELECT * FROM question_reg
WHERE courseid < '$id'
ORDER BY courseid DESC
LIMIT 1

I think there are a few things you need to consider.

  1. You need to mix the DB with some application logic. Why? Because you need to keep track of the history of displayed questions (Maybe a list containing the question and its selected answer).

  2. Now that you have the already displayed questions you need to use them in order to DISJOINT the Questions on DB and Questions Solved. (Just like a set intersection). Why in your App logic. Well, because you will be working with random select on db so you don't have any record of what was returned.

  3. Depending on the number of questions to solve I'ld suggest you to get at first the set of questions and cache them. Then, if you need to persist state (if there's some error or the user get disconnected) its easy.