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);
PHP MYSQL average score returning incorrectly
Moderator: General Moderators
Re: PHP MYSQL average score returning incorrectly
It sounds like you're off by one. Try using this:OurTown wrote:it gives me 50% rather than 100%. Can you tell me what I'm doing wrong?
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";
}Re: PHP MYSQL average score returning incorrectly
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);
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);