Reputation: 1598
Im looking for a way to add up all data for "awayscore" returned from a sql query in a while loop and add it to a variable. After the loop the total for awayscore needs to be printed on screen. Part of my code looks like this, it displays all match results from 2009 - present for two selected teams in a table.
while($row = mysql_fetch_array($query)){
$gamesplayed ++;
echo'<tr>';
echo '<td>'.$row['gamedate'].'</td>';
echo '<td>'.$row['hometeam'].'</td>';
echo'<td>'.$row['awayteam'].'</td>';
echo'<td>'.$row['homescore'].'</td>';
echo'<td>'.$row['awayscore'].'</td>';
if($row['homescore'] > $row['awayscore']){
$team1wins++;
echo'<td style="background-color:yellow">'.$row['hometeam'].'</td>';
}
else if($row['homescore'] < $row['awayscore'])
{$team2wins++;
echo'<td>'.$row['awayteam'].'</td>';
}
echo'</tr>';
}
I tried to add up the totals for "homescore" and "awayscore" by adding the following statment in the while loop
$totAwayPoints += $row['awayscore'];
$totHomePoints += $row['homescore'];
However when I print the two variables on screen after the loop I get the following error: undefined variable
Any idea what I am doing wrong, or any suggest what I can do to improve this will be greatly appreciated.
Upvotes: 0
Views: 1496
Reputation: 43765
Your question seems to be lacking some of the relevant code, but the issue to me sounds like you failed to initialize the variables in advance, so you are unable to add to them.
Declare the variables before the loop:
$totAwayPoints = 0;
$totHomePoints = 0;
while( //etc
and then add to them within the loop.
I feel confident this is the problem, as you wouldn't be getting a message about undefined variables if you had created them in advance.
Upvotes: 4