Kayode Agbede Kayode Agbede - 2 months ago 9
MySQL Question

Double iteration on mysql table

I am trying to display unique dates of submitted surveys and place the response in a great, good, fair or bad row. I'm not sure what the problem is with this code but it returns the most recent date only.Something like this

SurveyDate | Great | Good | Fair | Bad
2016-09-26 | 34 | 12 | 22 | 5
2016-08-24 | 10 | 5 | 12 | 3

<?php
$w = "select distinct(datetime) from clientsurvey order by datetime desc";
$zx = mysql_query($w);
if (mysql_num_rows($zx) < 1) {
echo "<tr><td colspan='5' style='text-align:center; color:#ff0000'>No survey records</td></tr>";
}
$great = 0;
$good = 0;
$fair = 0;
$bad = 0;
while ($z = mysql_fetch_array($zx)) {
$uniquedate = $z['datetime'];
$xx = "select * from clientsurvey where datetime like '%$uniquedate%'";
$zz = mysql_query($xx);
while ($zx = mysql_fetch_array($zz)) {
$clientrating = $zx['clientrating'];
$datetime = $zx['datetime'];
if ($clientrating === "Bad") {
$bad++;
}
if ($clientrating === "Fair") {
$fair++;
}
if ($clientrating === "Good") {
$good++;
}
if ($clientrating === "Great") {
$great++;
}
}
echo "<tr><td>$uniquedate</td><td>$great</td><td>$good</td><td>$fair</td><td>$bad</td></tr>";
$great = 0;
$good = 0;
$fair = 0;
$bad = 0;
}
?>

Answer

You can actually handle this directly in MySQL using a pivot query:

SELECT datetime AS SurveyDate,
       SUM(CASE WHEN clientrating = 'Great' THEN 1 END) AS Great,
       SUM(CASE WHEN clientrating = 'Good'  THEN 1 END) AS Good,
       SUM(CASE WHEN clientrating = 'Fair'  THEN 1 END) AS Fair,
       SUM(CASE WHEN clientrating = 'Bad'   THEN 1 END) AS Bad
FROM clientsurvey
GROUP BY datetime

PHP code:

$query = "SELECT datetime AS SurveyDate,".
         "SUM(CASE WHEN clientrating = 'Great' THEN 1 END) AS Great,".
         "SUM(CASE WHEN clientrating = 'Good'  THEN 1 END) AS Good,".
         "SUM(CASE WHEN clientrating = 'Fair'  THEN 1 END) AS Fair,".
         "SUM(CASE WHEN clientrating = 'Bad'   THEN 1 END) AS Bad".
         "FROM clientsurvey".
         "GROUP BY datetime";
$result = mysql_query($query);
echo "datetime, bad, fair, good, great";
while ($row = mysql_fetch_array($result)) {
    $datetime = $row['datetime'];
    $bad      = $row['Bad'];
    $fair     = $row['Fair'];
    $good     = $row['Good'];
    $great    = $row['Great'];
    echo $datetime.", ".$bad.", ".$fair.", ".$good.", ".$great;
}