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 ?>