I am using the following script to count records, the way I think it should be working should be.
'some heading' x4
but instead it is outputting 'some heading' 1x 1x 1x 1x
include("connectmysqli.php");
if (isset($_GET['questionnaireID'])) {$questionnaireID = $_GET['questionnaireID'];}else {$questionnaireID = '';}
echo '<p><strong>View Questionnaire Results</strong></p>';
$sql1 = <<<SQL
SELECT answer1, COUNT(answer1)
FROM `QuestionnaireAnswers`
WHERE questionnaireID='$questionnaireID'
GROUP BY answer1
SQL;
if(!$result1 = $db->query($sql1)){ die('There was an error running the query [' . $db->error . ']');}
while($row1 = $result1->fetch_assoc()){
echo $row1['COUNT(answer1)'] . ' X <strong>' . $answer1 . '</strong><br />';
}
Here is an example of the table
So using the above screen shot, the column answer1 when counted should be 2x , but what is actually displayed is 1x 1x
If I run the query from the answers in phpmyadmin I get :
You are attempting to use a MySQL function (COUNT
) in PHP. I have never seen such a usage. Use alias for count of answer1:
$sql1 = <<<SQL
SELECT answer1, COUNT(*) as cnt
FROM `QuestionnaireAnswers`
WHERE questionnaireID='$questionnaireID'
GROUP BY questionnaireID
SQL;
Then after fetch_assoc()
method use it as
echo $row1['cnt'];
Use COUNT(*)
instead of COUNT(answer1)
and you should be OK.
This is smart for two reasons: first, it can be a lot faster, and second, you're grouping by answer1
so you shouldn't count it.
Edit This is a summary query.
SELECT answer1, COUNT(*) AS cnt1
FROM `QuestionnaireAnswers`
WHERE questionnaireID='$questionnaireID'
GROUP BY answer1
It produces one row for each distinct value of answer1
, showing how many occurrences of that row are in the original table. The sample data you've shown contains just two rows. One of them has an answer of 2, the other has an answer of 8.