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

83 lines
2.5 KiB
PHP

<?php
require_once 'includes/header.php';
require_once 'db/config.php';
// Redirect if not logged in or if it's not a POST request
if (!isset($_SESSION['user_id']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: login.php');
exit();
}
// Basic validation
if (!isset($_POST['test_id']) || !is_numeric($_POST['test_id']) || !isset($_POST['answers']) || !is_array($_POST['answers'])) {
die("Invalid data submitted.");
}
$user_id = $_SESSION['user_id'];
$test_id = intval($_POST['test_id']);
$answers = $_POST['answers'];
$total_score = 0;
try {
$db = db();
// Get the scores for the selected options
$option_ids = array_values($answers);
$placeholders = implode(',', array_fill(0, count($option_ids), '?'));
$scoreStmt = $db->prepare("SELECT id, score FROM options WHERE id IN ($placeholders)");
$scoreStmt->execute($option_ids);
$scores = $scoreStmt->fetchAll(PDO::FETCH_KEY_PAIR);
// Begin transaction
$db->beginTransaction();
// Prepare statement for inserting or updating user answers
$answerStmt = $db->prepare(
"INSERT INTO user_answers (user_id, question_id, option_id) VALUES (:user_id, :question_id, :option_id)
ON DUPLICATE KEY UPDATE option_id = VALUES(option_id)"
);
// Calculate total score and insert individual answers
foreach ($answers as $question_id => $option_id) {
if (isset($scores[$option_id])) {
$total_score += $scores[$option_id];
}
// Insert the answer
$answerStmt->execute([
'user_id' => $user_id,
'question_id' => $question_id,
'option_id' => $option_id
]);
}
// Save the final score in the user_tests table
$userTestStmt = $db->prepare("
INSERT INTO user_tests (user_id, test_id, score)
VALUES (:user_id, :test_id, :score)
ON DUPLICATE KEY UPDATE score = :score
");
$userTestStmt->execute([
'user_id' => $user_id,
'test_id' => $test_id,
'score' => $total_score
]);
// Commit transaction
$db->commit();
// Redirect to results page
header("Location: test_results.php?test_id=" . $test_id);
exit();
} catch (PDOException $e) {
// Rollback on error
if ($db->inTransaction()) {
$db->rollBack();
}
// A generic error message is better for production
die("An error occurred while submitting your test. Please try again later. Error: " . $e->getMessage());
}
?>