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; } $stmt = $pdo->prepare(" SELECT q.id AS question_id, q.question_text, q.question_type, sa.answer_text FROM survey_answers sa JOIN questions q ON sa.question_id = q.id WHERE q.survey_id = ? "); $stmt->execute([$survey_id]); $answers = $stmt->fetchAll(PDO::FETCH_ASSOC); $chart_data = []; $text_answers = []; foreach ($answers as $answer) { $question_id = $answer['question_id']; $question_text = $answer['question_text']; $question_type = $answer['question_type']; $answer_text = $answer['answer_text']; if ($question_type === 'multiple-choice' || $question_type === 'checkboxes') { if (!isset($chart_data[$question_id])) { $chart_data[$question_id] = [ 'question_text' => $question_text, 'answers' => [], ]; } if ($question_type === 'checkboxes') { $selected_options = explode(',', $answer_text); foreach ($selected_options as $option) { $option = trim($option); if (!empty($option)) { if (!isset($chart_data[$question_id]['answers'][$option])) { $chart_data[$question_id]['answers'][$option] = 0; } $chart_data[$question_id]['answers'][$option]++; } } } else { // multiple-choice if (!isset($chart_data[$question_id]['answers'][$answer_text])) { $chart_data[$question_id]['answers'][$answer_text] = 0; } $chart_data[$question_id]['answers'][$answer_text]++; } } else { if (!isset($text_answers[$question_id])) { $text_answers[$question_id] = [ 'question_text' => $question_text, 'answers' => [], ]; } $text_answers[$question_id]['answers'][] = $answer_text; } } } catch (PDOException $e) { http_response_code(500); echo "Database error: " . htmlspecialchars($e->getMessage()); exit; } ?>