I am building a simple quiz program, using PHP and MYSQL.
The quiz is designed to display one question at a time; the questions are multiple-choice (each question has 4
When you ask your question to the user, a question is randomly selected from the database.
Then, the user submits your form, another question is randomly selected, and that's the question you are using to check the answer, instead of the question you asked to the user.
You need to add an hidden input in your form, that contains the question id
<input type="hidden" name="question_id" value="<?php echo $question_id ?>" />
And then when you check the answer, be sure to fetch the right question from the database
The code would look like this
<?php
// Check user answer for previous question
if (isset($_POST['submit'])) {
// Retrieve the id of the question you asked
$previous_question_id = (int) $_POST['question_id']; // cast to integer to prevent sql injection.
// Query database
$get_question = "SELECT * from questions_table where id = $previous_question_id";
$result_get_question = mysqli_query($conn, $get_question);
$row_get_question = mysqli_fetch_array($result_get_question);
// Assign database response to variables
$correct = $row_get_question['correct'];
$selected_radio = $_POST['response'];
if ($selected_radio == $correct)
echo "THAT ANSWER IS CORRECT";
else
echo "THAT ANSWER IS WRONG!";
}
// Load new question to ask to the user
$get_question = "SELECT * from questions_table order by rand() limit 1";
$result_get_question = mysqli_query($conn,$get_question);
$row_get_question = mysqli_fetch_array($result_get_question);
// assign thing we want to print in the template to variable
$question_id = $row_get_question['question_id'];
$question = $row_get_question['question'];
$a1 = $row_get_question['a1'];
$a2 = $row_get_question['a2'];
$a3 = $row_get_question['a3'];
$a4 = $row_get_question['a4'];
?>
<PASTE YOUR TEMPLATE HERE>