36629-vm/retake_test.php
Flatlogic Bot 20f916f31d v3
2025-12-08 05:38:25 +00:00

53 lines
1.5 KiB
PHP

<?php
require_once 'includes/header.php';
require_once 'db/config.php';
// Redirect if not logged in
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
// Check for test ID
if (!isset($_GET['test_id']) || !is_numeric($_GET['test_id'])) {
// Redirect to home or show an error
header('Location: index.php');
exit();
}
$test_id = intval($_GET['test_id']);
$user_id = $_SESSION['user_id'];
try {
$db = db();
// Start a transaction
$db->beginTransaction();
// Delete from user_answers
$stmt_answers = $db->prepare("DELETE FROM user_answers WHERE user_id = :user_id AND question_id IN (SELECT id FROM questions WHERE test_id = :test_id)");
$stmt_answers->execute(['user_id' => $user_id, 'test_id' => $test_id]);
// Delete from user_tests
$stmt_tests = $db->prepare("DELETE FROM user_tests WHERE user_id = :user_id AND test_id = :test_id");
$stmt_tests->execute(['user_id' => $user_id, 'test_id' => $test_id]);
// Commit the transaction
$db->commit();
// Redirect to the test page
header('Location: take_test.php?test_id=' . $test_id);
exit();
} catch (PDOException $e) {
// Rollback the transaction if something failed
if ($db->inTransaction()) {
$db->rollBack();
}
// You might want to log this error instead of showing it to the user
die("Database error while trying to reset the test. Please try again.");
}
// No need for footer as we are redirecting
?>