I have an array with names, goal differences and so on for football teams that I want to put in a table, but during the foreach the last key in the array is changed somehow.
Last two keys before foreach
[18] => Array
(
[team_code] => 4
[team_name] => Newcastle
[points] => 6
[goals_for] => 12
[goals_against] => 22
[goal_difference] => -10
)
[19] => Array
(
[team_code] => 7
[team_name] => Aston Villa
[points] => 4
[goals_for] => 9
[goals_against] => 17
[goal_difference] => -8
)
)
After foreach
[18] => Array
(
[team_code] => 4
[team_name] => Newcastle
[points] => 6
[goals_for] => 12
[goals_against] => 22
[goal_difference] => -10
)
[19] => Array
(
[team_code] => 4
[team_name] => Newcastle
[points] => 6
[goals_for] => 12
[goals_against] => 22
[goal_difference] => -10
)
)
My foreach looks like this
foreach ($teams as $team) {
$team_code = $team['team_code'];
$team_name = $team['team_name'];
$points = $team['points'];
$goals_for = $team['goals_for'];
$goals_against = $team['goals_against'];
$goal_difference = $team['goal_difference'];
if ($update_query = $conn->query("UPDATE teams SET points = $points, goals_for = $goals_for, goals_against = $goals_against, goal_difference = $goal_difference WHERE team_code = $team_code")) {
echo 'Updated '.$team_name.'<br>';
} else {
$update_query->error;
}
}
Why is the last key changed? It happens before the query is run, because the row doesn't get updated. All the others update as they should.