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