一种更简洁的方法来计算来自mysql db的调查响应

时间:2011-07-15 08:29:18

标签: php mysql survey

目前我使用此代码来计算调查回复:

$VERYHAPPY = mysql_query("SELECT * FROM answers, complete WHERE (answers.uniqueID = complete.uniqueID) AND (complete.timestamp) IS NOT NULL AND (answers.surveyID='$surveyID') AND QID = '$QID' AND response = 'VERY HAPPY' ");
$HAPPY = mysql_query("SELECT * FROM answers, complete WHERE (answers.uniqueID = complete.uniqueID) AND (complete.timestamp) IS NOT NULL AND (answers.surveyID='$surveyID') AND QID = '$QID' AND response = 'HAPPY' ");
$DONTKNOW = mysql_query("SELECT * FROM answers, complete WHERE (answers.uniqueID = complete.uniqueID) AND (complete.timestamp) IS NOT NULL AND (answers.surveyID='$surveyID') AND QID = '$QID' AND response = 'DONT KNOW' ");
$UNHAPPY = mysql_query("SELECT * FROM answers, complete WHERE (answers.uniqueID = complete.uniqueID) AND (complete.timestamp) IS NOT NULL AND (answers.surveyID='$surveyID') AND QID = '$QID' AND response = 'UNHAPPY' ");
$VERYUNHAPPY = mysql_query("SELECT * FROM answers, complete WHERE (answers.uniqueID = complete.uniqueID) AND (complete.timestamp) IS NOT NULL AND (answers.surveyID='$surveyID') AND QID = '$QID' AND response = 'VERY UNHAPPY' ");

 $VERYHAPPYcount = mysql_num_rows($VERYHAPPY);
 $HAPPYcount = mysql_num_rows($HAPPY);
 $DONTKNOWcount = mysql_num_rows($DONTKNOW); 
 $UNHAPPYcount = mysql_num_rows($UNHAPPY);
 $VERYUNHAPPYcount = mysql_num_rows($VERYUNHAPPY); 
  echo "VERY HAPPY = $VERYHAPPYcount</br>HAPPY = $HAPPYcount</br>DON'T KNOW = $DONTKNOWcount</br>UNHAPPY = $UNHAPPYcount</br>VERY UNHAPPY = $VERYUNHAPPYcount";  

你可以看到 - 它真的很乱!有更好的方法吗?我尝试过COUNT和GROUP BY,但无法让它们工作。感谢

1 个答案:

答案 0 :(得分:0)

你可以尝试这个SQL(我还没有测试过) -

SELECT count(*) as recordcount, response 
FROM answers, complete 
WHERE (answers.uniqueID = complete.uniqueID) 
AND (complete.timestamp) IS NOT NULL 
AND (answers.surveyID='$surveyID') 
AND QID = '$QID'
GROUP BY response

要将结果导入PHP,您可以尝试这样的事情(我无法测试PHP代码,所以我在下面的代码基于此代码 - http://php.net/manual/en/function.mysql-query.php并希望最好!下面的代码将几乎肯定包含错误,但希望能让你知道如何做到这一点)

//assign sql above to $query variable prior to doing this
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    echo $row['response'] & " = " & $ row['recordcount'] & "count</br>"
}