First array element getting overwritten by the second when getting data from db using PHP
I have a few lines of code that start something like this:
$trailheads = array();
// Then a db call with a query. Then loop through the results.
// This gives a diff value every time, so here we are still ok
$trailhead->trailhead_name = $row['trailhead_name'];
// Before the look iteration ends, I do something like this:
arra开发者_JS百科y_push ( $trailheads , $trailhead );
// But I could have done this with the same result:
$trailheads[] = $trailhead;
And once I exit the loop, I do print_r and it shows that the second of the two rows returned by the query over-wrote the first.
Here is the full version of the loop:
while($row = mysql_fetch_assoc($trailhead_result))
{
$trailhead->trailhead_name = $row['trailhead_name'];
$trailhead->park_id = $row['park_id'];
$trailhead->trailhead_id = $row['trailhead_id'];
$trailhead->trailhead_description = $row['trailhead_description'];
$trailhead->parking = $row['parking'];
$trailhead->lat = $row['lat'];
$trailhead->lng = $row['lng'];
$trailhead->is_free = $row['is_free'];
$trailhead->parking_spots = $row['parking_spots'];
$trailhead->cost_details = $row['cost_details'];
$trailheads[] = $trailhead;
}
If that's your full loop, then one problem is that you're not initializing $trailhead
inside the loop. Do this:
while($row = mysql_fetch_assoc($trailhead_result))
{
$trailhead = new trailhead();
$trailhead->trailhead_name = $row['trailhead_name'];
$trailhead->park_id = $row['park_id'];
$trailhead->trailhead_id = $row['trailhead_id'];
$trailhead->trailhead_description = $row['trailhead_description'];
$trailhead->parking = $row['parking'];
$trailhead->lat = $row['lat'];
$trailhead->lng = $row['lng'];
$trailhead->is_free = $row['is_free'];
$trailhead->parking_spots = $row['parking_spots'];
$trailhead->cost_details = $row['cost_details'];
$trailheads[] = $trailhead;
}
I have to assume that the object $trailhead
is a class called trailhead
. If it's not, use whatever class is correct in place of new trailhead()
.
精彩评论