prepare("SELECT title FROM surveys WHERE id = ?"); $stmt->execute([$survey_id]); $survey = $stmt->fetch(PDO::FETCH_ASSOC); if (!$survey) { http_response_code(404); echo "Error: Survey not found."; exit; } // Fetch all responses for this survey $stmt = $pdo->prepare("SELECT * FROM survey_responses WHERE survey_id = ? ORDER BY submitted_at DESC"); $stmt->execute([$survey_id]); $responses = $stmt->fetchAll(PDO::FETCH_ASSOC); // For each response, fetch the answers $responses_with_answers = []; foreach ($responses as $response) { $answer_stmt = $pdo->prepare(" SELECT sa.answer_text, q.question_text FROM survey_answers sa JOIN questions q ON sa.question_id = q.id WHERE sa.response_id = ? "); $answer_stmt->execute([$response['id']]); $answers = $answer_stmt->fetchAll(PDO::FETCH_ASSOC); $response['answers'] = $answers; $responses_with_answers[] = $response; } } catch (PDOException $e) { http_response_code(500); echo "Database error: " . htmlspecialchars($e->getMessage()); exit; } ?>