72 lines
2.0 KiB
PHP
72 lines
2.0 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();
|
|
|
|
|
|
|
|
// Calculate total score
|
|
foreach ($answers as $question_id => $option_id) {
|
|
if (isset($scores[$option_id])) {
|
|
$total_score += $scores[$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());
|
|
}
|
|
|
|
?>
|