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.'); }