php - How to select a specific value plus extra random values in a query?
I am pretty new to this but I am trying to make a quiz of 5 multiple choice questions. each question has 4 choices. I have the questions and their respective answer in a database. I am trying to randomize the questions and answers so each time a user takes the quiz it will show different questions.
Here is my code:
$qquery = "SELECT question from questions order by rand() limit 1";
$question = getvalue($qquery);
$aquery = "SELECT (SELECT answer from questions where question = '$question')
as right_ans, (select answer from questions where question != '$question')
order by rand() limit 4";
The getvalue(query) function returns the question string. I am using that in order to find the right answer on the database. The function also runs the query and displays the results. My second query isn't working. I would appreciate any input. Thanks!
Answer
Solution:
Try this new one, dont know, works with mysql or not.
Answer
Solution:
With your current schema you can try it this way with one query
Sample output:
Answer
Answer
Here is SQLFiddle demo
Obviously you read the question and the right answer once (e.g. from the the first) row and grab other 3 wrong answers from
{-code-2}
column while you iterate over the resultset in php.or you can go further and pack wrong answers in a delimited list
Sample output:
Answer
Answer
Here is SQLFiddle demo
Then in php you always have a single row resultset. And you can easily
explode()
wrong_answer
values.