-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubmit_exams.php
More file actions
39 lines (31 loc) · 1.25 KB
/
Copy pathsubmit_exams.php
File metadata and controls
39 lines (31 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
session_start();
require 'config.php';
if (!isset($_SESSION['id']) || $_SESSION['role'] !== 'student') { header('Location:index.php'); exit; }
$user_id = $_SESSION['id'];
$exam_id = intval($_POST['exam_id'] ?? 0);
$qstmt = $pdo->prepare("SELECT * FROM exam_questions WHERE exam_id = ?");
$qstmt->execute([$exam_id]);
$questions = $qstmt->fetchAll(PDO::FETCH_ASSOC);
$total = 0;
$score = 0;
// create submission
$pdo->beginTransaction();
$ins = $pdo->prepare("INSERT INTO exam_submissions (exam_id, user_id, score, total) VALUES (?, ?, 0, 0)");
$ins->execute([$exam_id, $user_id]);
$submission_id = $pdo->lastInsertId();
$insertAns = $pdo->prepare("INSERT INTO exam_answers (submission_id, question_id, chosen) VALUES (?, ?, ?)");
foreach ($questions as $q) {
$qid = $q['id'];
$chosen = $_POST["q$qid"] ?? null;
$insertAns->execute([$submission_id, $qid, $chosen]);
$total += intval($q['points']);
if ($chosen && $chosen === $q['correct_option']) {
$score += intval($q['points']);
}
}
$upd = $pdo->prepare("UPDATE exam_submissions SET score = ?, total = ? WHERE id = ?");
$upd->execute([$score, $total, $submission_id]);
$pdo->commit();
header("Location: exam_result.php?id={$submission_id}");
exit;