Page 1 of 1

PHP MYSQL average score returning incorrectly

Posted: Thu Mar 13, 2008 11:02 am
by OurTown
I'm having an issue with my php script. The way it's supposed to work is that it pulls quiz scores from the database, adds them up, then figures out the average score. When I'm using echo "$scoretotal" to see what it's adding up it gives me 100100 rather than 200.
So, when I have $scoretotal divide by the number of rows which is 2 it gives me 50% rather than 100%. Can you tell me what I'm doing wrong?

$result = mysql_query("SELECT * FROM $testname");
$numberofquestions = (mysql_num_fields ($result)-5);
$num_rows = mysql_num_rows($result);
for($i=1 ;$i<=$num_rows ; $i++)
{
$result2 = mysql_query("SELECT score FROM $testname WHERE id=$i");
$score = mysql_fetch_array($result2);
$scoretotal = $scoretotal + $score['score'];
echo "$scoretotal";
}
$average = round(($scoretotal/$num_rows),2);

Re: PHP MYSQL average score returning incorrectly

Posted: Thu Mar 13, 2008 11:28 am
by Chalks
OurTown wrote:it gives me 50% rather than 100%. Can you tell me what I'm doing wrong?
It sounds like you're off by one. Try using this:

Code: Select all

for($i=0 ;$i<$num_rows ; $i++)
{
$result2 = mysql_query("SELECT score FROM $testname WHERE id=$i");
$score = mysql_fetch_array($result2);
$scoretotal = $scoretotal + $score['score'];
echo "$scoretotal";
}
If that doesn't work, echo out $num_rows and make sure it's the value you expect.

Re: PHP MYSQL average score returning incorrectly

Posted: Thu Mar 13, 2008 1:50 pm
by OurTown
changing the i=1 to i=0 didn't work. It echos 0100100. The tests being displayed is 2 which is correct. The issue is having all the rows add up.

I've got it fixed. I used AVG(column) to get the average.

for($i=1 ;$i<=$num_rows ; $i++)
{
$result2 = mysql_query("SELECT AVG(score) FROM $testname");
$score = mysql_fetch_array($result2);
$scoretotal = $score['AVG(score)'];
}
$average = round(($scoretotal),2);