0

It looks like I can get the average of the whole array but not of each item in a array. I would like to avoid some loop. I use the function AVG() for it.

$sql_statement = "SELECT AVG(answer) AS averageanswer
                FROM answer2
                WHERE question_id
                IN(".implode(",", $qid).")
                AND answer <= 5
            ";

$dblink = mysql_connect($DBhost, $DBuser, $DBpassword);
mysql_select_db($DB,$dblink);
$qry = mysql_query($sql_statement,$dblink);

while($averageanswer=mysql_fetch_array($qry)) {
    $average[] = round($averageanswer['averageanswer']);
}

When I print the array this is the result:

Array ( [0] => 4 )

Did someone experience the same problem before or does someone know the solution for me? All tips are welcome!

4
  • What result are you expecting? We need to see the data in the DB. '4' could be a perfectly valid average. Commented Apr 24, 2011 at 11:33
  • The average of each item in the array $qid is 4. It is true that the output I get is 4. But I do not want 1 output of 4. My output should look like Array ( [0] => 4 [1] => 4 [2] => 4 [3] => 4 ). Commented Apr 24, 2011 at 11:41
  • What is "it"? What are you trying to achieve? Your code is broken so we can't figure out what you want to do from it. Commented Apr 24, 2011 at 12:01
  • 1
    BTW database don't have "arrays". Commented Apr 24, 2011 at 12:02

1 Answer 1

4

I presume you are wanting the Average results, per question. In which case:

$sql_statement = "SELECT AVG(answer) AS averageanswer
                FROM answer2
                WHERE question_id
                IN(".implode(",", $qid).")
                AND answer <= 5
                GROUP BY question_id
            ";

$dblink = mysql_connect($DBhost, $DBuser, $DBpassword);
mysql_select_db($DB,$dblink);
$qry = mysql_query($sql_statement,$dblink);

while($averageanswer=mysql_fetch_array($qry)) {
    $average[] = round($averageanswer['averageanswer']);
}

This will result in one row, per question_id, containing the average of answers for any row with that question_id

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.