This is my php code
<?php
include 'config.php';
$sql = "SELECT * FROM quiz where lesson = 5 order by rand() limit 20";
$result = mysqli_query($conn, $sql);
$quizQuestions = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$score = 0;
// Get the selected answer for the current question
$selectedAnswer = isset($_POST['answer']) ? $_POST['answer'] : -1;
// Check if the selected answer is correct
$currentQuestion = isset($_POST['currentQuestion']) ? $_POST['currentQuestion'] : 0;
$correctAnswer = $quizQuestions[$currentQuestion]['answer'];
if( $selectedAnswer == $correctAnswer){
$score++;
}
// Check if there are more questions
if ($currentQuestion < count($quizQuestions) - 1) {
// Display the next question
displayQuestion($currentQuestion + 1, $score);
} else {
// Display the final score
echo "Your score: $score out of " . count($quizQuestions);
}
} else {
// Display the first question
displayQuestion(0);
}
// Function to display a question
function displayQuestion($index, $score=0)
{
global $quizQuestions;
$question = $quizQuestions[$index]['question'];
$choices = array(
$quizQuestions[$index]['option_A'],
$quizQuestions[$index]['option_B'],
$quizQuestions[$index]['option_C'],
$quizQuestions[$index]['option_D']
);
echo '<div>';
echo '<form method="post">';
echo '<h3>' . $question . '</h3>';
foreach ($choices as $choiceIndex => $choice) {
echo '<label><input type="radio" name="answer" value="' . $choiceIndex . '">' . $choice . '</label><br>';
}
echo '<br>';
echo '<input type="hidden" name="currentQuestion" value="' . $index . '">';
echo '<input type="submit" class="next" value="Next">';
echo '</form>';
echo '<br>';
echo 'Score: ' . $score . ' out of ' . ($index + 1);
echo '</div>';
}
// Close the connection
mysqli_close($conn);
?>
I am working on multiple choice quiz application using php. The data is retrieved successfully from the database and displaying the questions one by one as well but if the answer is correct then also it is showing final answer as 0. Can any one please help me to tackle the problem?