I'm doing a simple php quiz game. I have the questions and answers stored in the database. The table structure of my tblQuiz is like this:
_id, question, answer1, answer2, answer3, correctanswer.
I have to randomly display them on the page.
This is what I've tried so far:
<!DOCTYPE html>
<html>
<head>
<title>Sample Quiz</title>
<?php
include 'db.php';
$stmt = $conn->prepare( "SELECT *
FROM tblquiz ORDER BY rand()" );
$stmt->execute();
?>
</head>
<body>
<?php
$number = 0;
for($i=0; $row = $stmt->fetch(); $i++){
$number++;
$id = $row['_id'];
$question = $row['question'];
$answer1 = $row['answer1'];
$answer2 = $row['answer2'];
$answer3 = $row['answer3'];
$correctanswer = $row['correctanswer'];
?>
<h4> <?php echo $number . ".) " . $question; ?></h4>
<label><input type="radio" value="<?php echo $answer1; ?>" name="<?php echo $question; ?>"> <?php echo $answer1; ?></label>
<label><input type="radio" value="<?php echo $answer2; ?>" name="<?php echo $question; ?>"> <?php echo $answer2; ?></label>
<label><input type="radio" value="<?php echo $answer3; ?>" name="<?php echo $question; ?>"> <?php echo $answer3; ?></label>
<label><input type="radio" value="<?php echo $correctanswer; ?>" name="<?php echo $question; ?>"> <?php echo $correctanswer; ?></label>
<?php
}
?>
<br />
<br />
<input type="submit" value="Submit" name="submit">
</body>
</html>
But I can't seem to get what I want to achieve, only the questions are being randomly displayed. I also want to randomly position the answers themselves.
Im newbie in PHP so I need your help. Thanks a lot in advance to those who will help.
Use this
Editor Fiddle : http://www.phpfiddle.org/lite/code/rgc-zfj
Result Fiddle : http://www.phpfiddle.org/api/run/rgc-zfj
In your code
Store all your answers in a single array and then iterate the array randomly and print your answer lables because you can not optimize your query to select the columns randomly.
Try this: