prepare('SELECT * FROM student_exams WHERE id = ? AND student_id = ?'); $stmt->execute([$student_exam_id, $user_id]); $student_exam = $stmt->fetch(); if (!$student_exam) { echo "You are not assigned to this exam."; exit(); } // Prevent re-taking a completed exam if ($student_exam['status'] === 'completed') { echo "You have already completed this exam."; // Maybe redirect to a results page in the future echo '
Back to Exams'; exit(); } // Fetch exam details $stmt = $pdo->prepare('SELECT * FROM exams WHERE id = ?'); $stmt->execute([$student_exam['exam_id']]); $exam = $stmt->fetch(); // Fetch exam questions $stmt = $pdo->prepare('SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY id ASC'); $stmt->execute([$exam['id']]); $questions = $stmt->fetchAll(); // Handle exam submission if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['answers'])) { $answers = $_POST['answers']; $pdo->beginTransaction(); try { foreach ($answers as $question_id => $answer_text) { // Use INSERT ... ON DUPLICATE KEY UPDATE to prevent duplicate answer submissions $sql = 'INSERT INTO student_answers (student_exam_id, question_id, answer_text) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE answer_text = VALUES(answer_text)'; $stmt = $pdo->prepare($sql); $stmt->execute([$student_exam_id, $question_id, trim($answer_text)]); } // Mark exam as completed $stmt = $pdo->prepare('UPDATE student_exams SET status = \'completed\' WHERE id = ?'); $stmt->execute([$student_exam_id]); $pdo->commit(); header('Location: exams.php'); exit(); } catch (Exception $e) { $pdo->rollBack(); // Log error properly in a real application die("An error occurred while submitting your exam. Please try again. Error: " . $e->getMessage()); } } // If student is starting the exam, mark it as 'in-progress' if ($student_exam['status'] === 'assigned') { $stmt = $pdo->prepare('UPDATE student_exams SET status = \'in-progress\' WHERE id = ?'); $stmt->execute([$student_exam_id]); } ?> Take Exam: <?php echo htmlspecialchars($exam['name']); ?>

$q): ?>

Question :

This exam has no questions.