I have a table called answers with 2 rows:
questionid – answer
as you can probably guess questionid stores the question id number and answer stores the answer, the answers are just numbers 1 to 8
I want to display the top answer.
eg:
questionid – answer
4 - 7
4 - 3
4 - 3
2 - 3
6 - 7
7 - 1
9 - 8
1 - 5
top answer = 3
i’ve tried:
SELECT answer FROM answers WHERE questionid='$qid' ORDER BY answer DESC LIMIT 1
and
SELECT DISTINCT answer FROM answers WHERE questionid='$qid' ORDER BY answer DESC LIMIT 1
$qid = page id ie: /question.php?qid=4
but both return incorrect.
Update:
Is there away of showing the result without using:
while($row = mysql_fetch_array($result)) {
// stuff here
}
as I just want to show 1 result (ie the top answer) based on $qid
There are multiple ways to do this (
HAVING(),WHERE,MAX(), etc) The commonality isGROUP BY.This will return:
Read more about
GROUP BY.UPDATE
Seems you modified your question after I posted this answer.
If you want to limit the query to a specific question, add a
WHEREclause as the other questions.Note: Be mindful of SQL Injection.
When you only have 1 record, you can forego the
whileloop and just access the top result.Note: You’ll like want to do more error checking (e.g. ensure a result was returned). Also, don’t use
mysql_*functions as they are now deprecated. Use MySQLi or PDO instead.