I have a question table in my database which consists the following columns
question number
which ranges from 1 to 150.question text
text for 4 options
as A,B,C,and Danswer option
(either a,b,c or d)
Now i want to make a quiz where there will be 15 questions from these 150 questions and each question will be randomly selected from the pool of these 150 questions and also all these 15 questions must be unique i have used the followig approach but with this approach i am getting random question but there is a possibility of 2 same questions.
$n1=mt_rand(1,150);
$q=mysqli_query($mysqli,"select * from quiz WHERE qno = '".$n1."'");
I have also try to use DISTINCT but with this also I get two or more same questions:-
$n1=mt_rand(1,150);
$q=mysqli_query($mysqli,"select DISTINCT qno,ques,a,b,c,d,ans from quiz where qno='".$n1."' " );
i am using php language
Best Answer
Preliminary: I assume this is your table:
You can let MySQL do the hard work for you, and just execute the following SELECT statement, that will sort randomly all your table (i.e.: it is actually shuffling the rows), and just choose the top 5 rows (NOTE: I've used 5 instead of 15 for the sake of simplicity).
The key point: instead of generating a random number from PHP, let the database deal with the random numbers...
(Converting this to PHP code is quite straightforward)
You will get something like:
Repeating the same query will give you a different set of questions (although some might have already be asked):
When you work with a database, it is normally a good idea to let the database give you the complete answer to your problem, instead of looping in your code.
You can see all the setup and some more executions at dbfiddle here
References: