50 lines
1.5 KiB
PHP
50 lines
1.5 KiB
PHP
<?php
|
|
require_once 'db/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$survey_id = filter_input(INPUT_POST, 'survey_id', FILTER_VALIDATE_INT);
|
|
$answers = $_POST['answers'] ?? [];
|
|
|
|
if (!$survey_id) {
|
|
http_response_code(400);
|
|
die('Bad request: survey_id is required.');
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$pdo->beginTransaction();
|
|
|
|
// 1. Create a new survey response
|
|
$stmt = $pdo->prepare("INSERT INTO survey_responses (survey_id) VALUES (?)");
|
|
$stmt->execute([$survey_id]);
|
|
$response_id = $pdo->lastInsertId();
|
|
|
|
// 2. Save each answer
|
|
$stmt = $pdo->prepare("INSERT INTO survey_answers (response_id, question_id, answer_text) VALUES (?, ?, ?)");
|
|
foreach ($answers as $question_id => $answer_text) {
|
|
if (is_array($answer_text)) {
|
|
// For checkboxes, implode the array into a string
|
|
$answer_text = implode(', ', $answer_text);
|
|
}
|
|
$stmt->execute([$response_id, $question_id, $answer_text]);
|
|
}
|
|
|
|
$pdo->commit();
|
|
|
|
// Redirect to a success page
|
|
header('Location: survey_success.php?response=true');
|
|
exit;
|
|
|
|
} catch (PDOException $e) {
|
|
if ($pdo->inTransaction()) {
|
|
$pdo->rollBack();
|
|
}
|
|
// In a real app, you'd log this error
|
|
http_response_code(500);
|
|
die('Database error: ' . $e->getMessage());
|
|
}
|
|
} else {
|
|
http_response_code(405);
|
|
die('Method not allowed.');
|
|
}
|