PHP MYSQL average score returning incorrectly

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
OurTown
Forum Newbie
Posts: 2
Joined: Thu Mar 13, 2008 11:00 am

PHP MYSQL average score returning incorrectly

Post 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);
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

Re: PHP MYSQL average score returning incorrectly

Post 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.
OurTown
Forum Newbie
Posts: 2
Joined: Thu Mar 13, 2008 11:00 am

Re: PHP MYSQL average score returning incorrectly

Post 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);
Post Reply