0

I have answers from a database and i can count 1 now but i want to show the amount of times a answer is chosen. I have no qlue how to do that. For instance I want to count the amount of times 'answer_id' (the id of the answer) 1 and 2 are answered in 'question_id'(the question)

I tried setting a different if while above it but that didn't work out for me.The database

<?php  
$conn = mysqli_connect('localhost', 'root','','survey_cms_4people');
if (!$conn){
    echo "DATABSE ERROR!";
}

$variable = 1;
$countAnswerQuery = "SELECT COUNT(`answer_id`) FROM survey_answers WHERE question_id=$variable AND answer_id=$variable ";
$countanswerresult = mysqli_query($conn, $countAnswerQuery);
while ($row = mysqli_fetch_array($countanswerresult)) {
    echo $row[0];
}


?> 

I want to be able to count them automaticly and not write a sql query for every question / answer.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

2 Answers2

1

For instance I want to count the amount of times 'answer_id' (the id of the answer) 1 and 2 are answered in 'question_id'(the question)

You can aggregate the results by question_id and answer_id to find out how many time each answer was choosen for each question, like:

SELECT question_id, answer_id, COUNT(*) cnt
FROM survey_answers 
GOUP BY question_id, answer_id

If yiou want to filter on a given question, you can add a WHERE clause:

SELECT question_id, answer_id, COUNT(*) cnt
FROM survey_answers 
WHERE question_id = ?
GOUP BY question_id, answer_id
GMB
  • 216,147
  • 25
  • 84
  • 135
1

You want to group by based on the answer id.

SELECT answer_id, COUNT(*) as count, question_id FROM survey_answers WHERE survey_id = $survey GROUP BY question_id , answer_id ORDER BY count DESC;

This will show you a count of all answers from all questions from a given survey.

This is probably a duplicate of:

MySQL: Count the occurrences of DISTINCT values

Rentabear
  • 300
  • 2
  • 11