ThePixelPony
ThePixelPony

Reputation: 741

Mysql Randomise Rows for Quiz

I have the following table structure:

Id Question Answer1 Answer2 Answer3 Answer4

Answer1 is always the correct answer, so I'd like to be able to display the four Answers in a random order using PHP.

How would this be possible?

Upvotes: 0

Views: 166

Answers (5)

CodeBird
CodeBird

Reputation: 3858

You can do it using php shuffle function like this,:

First you create an array of answers $answers then you shuffle this array shuffle($answers);

   $query=mysqli_query($db_conn, "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM questions_table WHERE id=1");

   $array=mysqli_fetch_assoc($query);
   $question=$array['Question'];
   $answers=array($array['Answer1'], $array['Answer2'], $array['Answer3'], $array['Answer4']);
   shuffle($answers);

Upvotes: 3

user2298995
user2298995

Reputation: 2163

I'd suggest getting results into array and then shuffle them with the following code (if you're using prepared statements, and you better use them):

$SQL = $db -> prepare("SELECT * FROM table WHERE id = :id");
$SQL -> execute(array(':id' => $id));

$results = $SQL -> fetch();
$question = $results['question'];

$answers = array($results['answer1'],$results['answer2'],$results['answer3'],$results['answer4'];

shuffle($answers);

Upvotes: 2

IROEGBU
IROEGBU

Reputation: 948

You table structure will make management of the database a huge problem in future.
With your present design, select your questions normally then place answers in an array and then shuffle($answers) will shuffle the answers.
Correct Solution will be to normalize your database, separate answers from questions. Use question_id to link questions to their answers. It will make your database design very flexible and management will be a lot easier.

Upvotes: 1

Gus de Boer
Gus de Boer

Reputation: 401

You will not be able to do this with MYSQL because the answers are all in the same row. As ThePixelPony you should use the shuffle function in PHP

Upvotes: 0

vanion
vanion

Reputation: 126

Put Answers into array, and than shuffle array using: shuffle

Upvotes: 3

Related Questions