You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
Code2C/quiz.php

152 lines
5.3 KiB

<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "user";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch 5 random questions from the database
$sql = "SELECT * FROM questions ORDER BY RAND() LIMIT 5";
$result = $conn->query($sql);
$questions = [];
while ($row = $result->fetch_assoc()) {
$questions[] = $row;
}
// Store correct answers in session
$correct_answers = [];
foreach ($questions as $index => $question) {
$correct_answers[] = $question['correct_option'];
}
$_SESSION['correct_answers'] = $correct_answers;
// Initialize the score if it's not already in session
if (!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$current_question_index = $_POST['current_question_index'];
$answer = $_POST['answer'];
// Check if the answer is correct and increment the score
if (isset($_SESSION['correct_answers'][$current_question_index]) && $answer == $_SESSION['correct_answers'][$current_question_index]) {
$_SESSION['score']++; // Increment score in session
}
// Move to the next question or finish if it's the last question
$next_question_index = $current_question_index + 1;
if ($next_question_index < count($questions)) {
echo json_encode([
'next_question_index' => $next_question_index,
'score' => $_SESSION['score'],
'next_question' => $questions[$next_question_index]
]);
} else {
// Redirect to the result page after the last question
header("Location: result.php");
exit();
}
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<link rel="stylesheet" type="text/css" href="quiz1.css">
</head>
<body>
<div class="quiz-container">
<h1>Welcome to the Quiz!</h1>
<div id="quiz-form">
<!-- Questions will appear dynamically here -->
</div>
</div>
<script>
const questions = <?php echo json_encode($questions); ?>;
const totalQuestions = questions.length;
let currentQuestionIndex = 0;
let score = <?php echo isset($_SESSION['score']) ? $_SESSION['score'] : 0; ?>;
// Function to display a question
function displayQuestion() {
const question = questions[currentQuestionIndex];
const quizForm = document.getElementById('quiz-form');
// Check if it's the last question
const isLastQuestion = currentQuestionIndex === totalQuestions - 1;
quizForm.innerHTML = `
<form id="quiz-form-${currentQuestionIndex}">
<p>${question.question}</p>
<label>
<input type="radio" name="answer" value="A" required>
${question.option_a}
</label><br>
<label>
<input type="radio" name="answer" value="B">
${question.option_b}
</label><br>
<label>
<input type="radio" name="answer" value="C">
${question.option_c}
</label><br>
<label>
<input type="radio" name="answer" value="D">
${question.option_d}
</label><br>
${
isLastQuestion
? `<a href="result.php" class="submit-link">Submit</a>`
: `<button type="submit">Next</button>`
}
</form>
`;
document.getElementById(`quiz-form-${currentQuestionIndex}`).addEventListener('submit', function(event) {
event.preventDefault();
const selectedAnswer = document.querySelector(`input[name="answer"]:checked`);
if (selectedAnswer) {
const answer = selectedAnswer.value;
// Send the current answer and question index to PHP via AJAX
fetch('quiz.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `answer=${answer}&current_question_index=${currentQuestionIndex}`
})
.then(response => response.json())
.then(data => {
score = data.score;
if (data.next_question_index < totalQuestions) {
currentQuestionIndex = data.next_question_index;
displayQuestion();
} else {
window.location.href = 'result.php'; // Redirect after the last question
}
});
} else {
alert('Please select an answer!');
}
});
}
// Start the quiz by displaying the first question
displayQuestion();
</script>
</body>
</html>