I am new to PHP, so I apologise if my question is quite primitive. I have made a quiz in PHP, and I intend for the quiz to find the correct answer for the currently displayed question. When the user submits an answer, the program should check if the answer submitted by the user matches the correct answer. However, my quiz changes the 'correctAnswer' variable before a point is awarded for a correct answer. I'm not sure how to fix this.
<?php
include('connect_db.php');
$sqlstmt = 'SELECT * FROM quiz ORDER BY RAND() LIMIT 1';
$res = mysqli_query($dbc, $sqlstmt);
while ($row = mysqli_fetch_assoc($res)) {
$CorrectAnswer = $row['CorrectAnswer'];
echo $CorrectAnswer;
?>
<html>
<head>
<style>
h1 {
text-align: center;
}
.answer {
display: flex;
margin-inline: auto;
margin-bottom: 1rem;
}
.button {
margin-top: 1rem;
}
fieldset {
display: flex;
flex-direction: column;
justify-content: center;
width: 50rem;
margin-inline: auto;
}
</style>
</head>
<body>
<h1>Quiz</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" align="center" id='myForm'>
<fieldset >
<legend>Question:</legend><br>
<p><?php echo $row['Question']; ?></p><br>
<div class="answer">
<input type="radio" id="answer1" name="answer" value="<?php echo $row['Answer1']; ?>"><br>
<label for="answer1"><?php echo $row['Answer1']; ?></label>
</div>
<div class="answer">
<input type="radio" id="answer2" name="answer" value="<?php echo $row['Answer2']; ?>"><br>
<label for="answer2"><?php echo $row['Answer2']; ?></label>
</div>
<div class="answer">
<input type="radio" id="answer3" name="answer" value="<?php echo $row['Answer3']; ?>"><br>
<label for="answer3"><?php echo $row['Answer3']; ?></label>
</div>
<div class="answer">
<input type="radio" id="answer4" name="answer" value="<?php echo $row['Answer4']; ?>"><br>
<label for="answer4"><?php echo $row['Answer4']; ?></label>
</div>
</fieldset>
<input class="button" type="submit" value="Submit">
</form>
<script>
function validateForm() {
var radios = document.getElementsByName('answer');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("You must select an option!");
return formValid;
}
var form = document.getElementById("myForm");
form.onsubmit = validateForm;
</script>
<?php
if (isset($_POST['answer'])) {
$selectedAnswer = $_POST['answer'];
echo $CorrectAnswer,$selectedAnswer;
if ($selectedAnswer == $CorrectAnswer)
echo '+1 pt';
}
}
?>
</body>
</html>
I have tried changing the order that my variables are declared, thinking that this would match up the correct answer with the submitted answer, but I'm in my second week of learning PHP properly so I didn't really know what I was doing or what I was expecting.