diff --git a/assets/pasted-20251015-181829-ed77e158.png b/assets/pasted-20251015-181829-ed77e158.png new file mode 100644 index 0000000..335faa9 Binary files /dev/null and b/assets/pasted-20251015-181829-ed77e158.png differ diff --git a/view_responses.php b/view_responses.php index c85e422..88b1dfe 100644 --- a/view_responses.php +++ b/view_responses.php @@ -13,7 +13,6 @@ if (!$survey_id) { try { $pdo = db(); - // Fetch survey title $stmt = $pdo->prepare("SELECT title FROM surveys WHERE id = ?"); $stmt->execute([$survey_id]); $survey = $stmt->fetch(PDO::FETCH_ASSOC); @@ -24,24 +23,58 @@ try { exit; } - // Fetch all responses for this survey - $stmt = $pdo->prepare("SELECT * FROM survey_responses WHERE survey_id = ? ORDER BY submitted_at DESC"); + $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]); - $responses = $stmt->fetchAll(PDO::FETCH_ASSOC); + $answers = $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; + $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) { @@ -57,6 +90,9 @@ try {