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