76 lines
2.3 KiB
PHP
76 lines
2.3 KiB
PHP
<?php
|
|
require_once 'db/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
header('Location: create_survey.php');
|
|
exit;
|
|
}
|
|
|
|
$title = trim($_POST['title'] ?? '');
|
|
$description = trim($_POST['description'] ?? '');
|
|
$questions = $_POST['questions'] ?? [];
|
|
|
|
if (empty($title) || empty($questions)) {
|
|
// Basic validation: Title and at least one question are required.
|
|
// In a real app, you'd want more robust validation and user feedback.
|
|
die('Error: Survey title and at least one question are required.');
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$pdo->beginTransaction();
|
|
|
|
// 1. Insert the survey
|
|
$stmt = $pdo->prepare("INSERT INTO surveys (title, description) VALUES (?, ?)");
|
|
$stmt->execute([$title, $description]);
|
|
$surveyId = $pdo->lastInsertId();
|
|
|
|
// 2. Insert the questions
|
|
$questionStmt = $pdo->prepare(
|
|
"INSERT INTO questions (survey_id, question_text, question_type, options) VALUES (?, ?, ?, ?)"
|
|
);
|
|
|
|
foreach ($questions as $question) {
|
|
$text = trim($question['text'] ?? '');
|
|
$type = trim($question['type'] ?? '');
|
|
$options = $question['options'] ?? [];
|
|
|
|
if (empty($text) || empty($type)) {
|
|
// Skip invalid/empty questions
|
|
continue;
|
|
}
|
|
|
|
// For choice-based questions, ensure options are provided and encode them as JSON
|
|
$optionsJson = null;
|
|
if (($type === 'multiple-choice' || $type === 'checkboxes')) {
|
|
// Filter out empty option strings
|
|
$validOptions = array_filter($options, function($val) {
|
|
return trim($val) !== '';
|
|
});
|
|
if (empty($validOptions)) {
|
|
// If no valid options, skip this question
|
|
continue;
|
|
}
|
|
$optionsJson = json_encode($validOptions);
|
|
}
|
|
|
|
$questionStmt->execute([$surveyId, $text, $type, $optionsJson]);
|
|
}
|
|
|
|
$pdo->commit();
|
|
|
|
// Redirect to a success page
|
|
header("Location: survey_success.php?id=" . $surveyId);
|
|
exit;
|
|
|
|
} catch (PDOException $e) {
|
|
// If anything goes wrong, roll back the transaction
|
|
if ($pdo->inTransaction()) {
|
|
$pdo->rollBack();
|
|
}
|
|
// In a real app, log this error instead of showing it to the user
|
|
die("Database error: " . $e->getMessage());
|
|
} catch (Exception $e) {
|
|
die("An unexpected error occurred: " . $e->getMessage());
|
|
}
|