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()); } ?>