How to select question from mysql tables randomly ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JosephHanh
Forum Newbie
Posts: 3
Joined: Wed Oct 15, 2014 8:36 am

How to select question from mysql tables randomly ?

Post by JosephHanh »

I am working on a quiz app

image 1 shows the index.php page
image 2 shows the first question
image 3 shows the second question
image 4 shows the third question
image 5 shows the result after completing the quiz
image 6 shows the database 'quizzer' and its tables
image 7 shows the 'questions' table
image 8 shows the 'choices' table

THIS LINK CONTAIN ALL THE CODE (and images) I HAVE DONE SO FAR

https://www.mediafire.com/folder/g5ao7f5q0fe6y/quiz

1.Now my question is how to select the question RANDOMLY from 'questions' table along with 'choices' (by adding code to the existing file or create a new one).

2.If user refresh/reload the page before starting ('Start Quiz') or click 'Take Again' after finishing the quiz, the question should appear randomly.

3.Basically I want to change the order of question appearing in the browser each time I refresh.

4.My work so far is mentioned above.........Please help me with this "RANDOM" problem !!

P.S - Will it be possible, by creating a random function in PHP which will check for repeat questions in a session and check for the 'id' of the question and if it is new display it on the page.

If so what should I do and if no then how to do?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How to select question from mysql tables randomly ?

Post by Celauran »

Might be easiest to pull down all the questions at once, store them in an array, shuffle it, then iterate over it.
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

Re: How to select question from mysql tables randomly ?

Post by pbs »

You can use SELECT query with ORDER BY RAND() to get random question from table

Code: Select all

SELECT * FROM questions ORDER BY RAND()
and if you want specific number of questions, then you can use LIMIT
JosephHanh
Forum Newbie
Posts: 3
Joined: Wed Oct 15, 2014 8:36 am

Re: How to select question from mysql tables randomly ?

Post by JosephHanh »

doesn't work that way RAND () :(
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How to select question from mysql tables randomly ?

Post by requinix »

JosephHanh wrote:doesn't work that way RAND () :(
Sure it does.

"It doesn't work" is useless to us. Describe what's actually going wrong.
Post Reply