34619-vm/survey_submit.php
2025-10-03 13:03:26 +00:00

64 lines
1.7 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/security.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("Location: index.php");
exit;
}
if (!validate_csrf_token()) {
die('CSRF token validation failed.');
}
$survey_id = $_POST['survey_id'] ?? null;
$answers = $_POST['answers'] ?? [];
if (!$survey_id || empty($answers)) {
// Or redirect to an error page
die("Invalid submission.");
}
$pdo = db();
try {
// Start a transaction
$pdo->beginTransaction();
// 1. Create a new response record
$response_stmt = $pdo->prepare("INSERT INTO responses (survey_id) VALUES (?)");
$response_stmt->execute([$survey_id]);
$response_id = $pdo->lastInsertId();
// 2. Insert each answer
$answer_stmt = $pdo->prepare("INSERT INTO answers (response_id, question_id, answer_value) VALUES (?, ?, ?)");
foreach ($answers as $question_id => $value) {
if (is_array($value)) {
// Handle checkbox arrays
$answer_value = implode(", ", $value);
} else {
$answer_value = $value;
}
if ($answer_value !== '') {
$answer_stmt->execute([$response_id, $question_id, $answer_value]);
}
}
// Commit the transaction
$pdo->commit();
// Redirect to a thank you page
header("Location: thank_you.php");
exit;
} catch (PDOException $e) {
// Roll back the transaction if something failed
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
// In a real app, log the error and show a user-friendly error page
die("Database error occurred while submitting your survey. Please try again later.");
}