4

I am making a quiz where I stored in a table questions and each time one question is asked I want another question to show. I have tried using rand():

select * from quiz order by rand() LIMIT 1

but the rows are being repeated.

Is there anything else I can use where I can get random rows but without getting same questions again?

4
  • 1
    For how long must they not repeat? Is there a limited number of questions? Do you want your user to go through all questions in the database once before seeing a duplicate? Commented Oct 2, 2012 at 7:06
  • From performance point of view is in general bad idea to use ORDER BY RAND() statement. Anyway if you want to use it, just add grouping in your query, for example GROUP BY quiz_id or some other unique identifier in order to get rid of duplicates. Commented Oct 2, 2012 at 7:06
  • yes i want the user to go through all questions once Commented Oct 2, 2012 at 7:08
  • 1
    Then just select all data a shuffle the results with php. Commented Oct 2, 2012 at 7:09

4 Answers 4

2

You could use sessions and your quiz id.

For example

select * from quiz order by rand() LIMIT 1

add in session quiz the quiz id:

if(!$_SESSION['quiz']) { $_SESSION['quiz'] = array(); }
$_SESSION['quiz'][] = $row['id'];

and call NOT IN:

$session = implode(", ", $_SESSION['quiz']);
$query = "select * from quiz WHRE `id` NOT IN (".$session.") order by rand() LIMIT 1";
Sign up to request clarification or add additional context in comments.

Comments

1

Just get the id of the previous returned row and exclude it from future queries.

select * from quiz WHERE id NOT :previous_id order by rand() LIMIT 1

Comments

1

If you require the user to go through all questions once in a random order, you'll have to keep track of an individual "playlist" for each user. Preferably using sessions:

session_start();

if (!$_SESSION['ids']) {
    $_SESSION['ids'] = $db->getAllQuestionIdsFromTheDatabase();
                    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                    // Leaving this up to you.

    shuffle($_SESSION['ids']);

    // $_SESSION['ids'] should now look like array(42, 12, 75, ...);
}

$question = $db->getQuestionById(array_shift($_SESSION['ids']));
...

You can do the randomization either in the database using ORDER BY RAND() or in PHP using shuffle, either is fine.

Comments

0

Yes, you could select all the rows (or some of them) and use shuffle() mainly because ORDER BY RAND() is really resource unfriendly and it actually re-queries each row of your table, assigns a random number ID and then delivers the results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.