开发者

how to randomize retrieval of question from database?

.i have the following code:

<?
session_start();
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';

mysql_connect($host,$user,$pw); 
mysql_select_db($db);

$result = mysql_query("SELECT * FROM questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
$_SESSION['totalquestions']=$num_rows;
while($row = mysql_fetch_assoc($result))
{
    $array[] = $row;
}

//Start the form
echo '<form method="post" action="result.php">';

for($i=0; $i<=($num_rows-1); $i++)
{
  //Render a question + the answer choices
  echo $array[$i]['Title']."<br />\n";
  for ($j=1;$j<=4;$j++) 
  {
    echo "<input type=\"radio\" name=\开发者_StackOverflow中文版"ans$i\" value=\"$j\">".
      $array[$i]['Answer'.$j]."<br />\n";
  }
}

//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";
?>

.the code above displays all the questions and their corresponding choices of answers which are retrieved from the database. my question is, how do you randomize the display of questions and display only 5 at a time and upon clicking a next button the next five will be displayed. Thanks in advance!


You can use LIMIT m,n to both limit the number of results you get and offset the results by a given amount.

Now you could do something like:

 SELECT * FROM questions WHERE QuizID=1 LIMIT $page,5;

Where you calculate the $page based on a $_GET variable. But this won't solve your randomness.

You could always seed RAND($key) by a given key that you save in your session so you could ORDER BY RAND($key) and use the above limit technique.

Probably the simplest to implement would be to get the entire result set, shuffle it and cache it. Then use a php to show only a specific chunk of the cache.

Since this is related to pagination. Let me tell you, LIMIT m,n may not be as fast as it sounds. Learn how to improve it and read more about Efficient Pagination Using MySQL


SELECT * FROM questions WHERE QuizID=1 ORDER BY RAND() LIMIT 5

Will get you 5 random rows. This isn't super-efficient for a very large table, but I'm guessing that's not your case.


A potential approach would be:

  1. Fetch the question IDs from the database when you detect a new user/on the 1st question via ORDER BY RAND() LIMIT 5 in SQL.

  2. Store these in the $_SESSION.

  3. Iterate through the question IDs in the $_SESSION, loading the full question data from the DB via the ID.


Try this :

here is code to get results :

    $total = @mysql_num_rows(mysql_query("SELECT * FROM questions WHERE QuizID=1"));
    $per_page = 5;
    $page = $_GET['page'];
    $query = "SELECT * FROM questions WHERE QuizID=1 , id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT " . mysql_real_escape_string($per_page) ." OFFSET " . mysql_real_escape_string($page * $per_page) . "";

here is code to "next page" :

    if($total >= ($page * $per_page))
    {
      echo '<a href="?page='.$page+1.'" >Next Page</a>';
     }

maybe you have to change something in my code, because i haven't tried it to see if it works.


Many of these answers seem to be overlooking the fact that, each time you send a request to the server, you are generating a brand randomised list of questions, and then selecting 5 of those, based on your current page.
This means that you may get repeated questions and means that you can't go back and forth up the list, i.e. it's not pagination, it's just 5 random questions each time.

One way to deal with this is to generate a randomized array of numbers that correspond to the key field of the question table. This is then stored in a persistent manner on the server and associated with a key that is passed back to the client (the session ID, perhaps).

Then, when the user accesses a page, the session ID comes in; this is used to identify the randomized array; the $page_num is used as an index into the array:

   $question_ids = array_slice($randomized_array, ($page_num - 1)*5, 5);

Next, you'd grab your questions using:

   $ids_for_query = array_map('mysql_real_escape_string', array_values($question_ids));
   mysql_query("SELECT * FROM questions WHERE id IN (".implode(',', $ids_for_query ).")");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜