I have the following code:
$result = mysql_query("SELECT * FROM events",$db);
$rowcheck = mysql_num_rows($result);
$allevents = array();
echo "<br>Display events: ($rowcheck)";
$i = '0';
while ($row_user = mysql_fetch_assoc($result)){
$allevents[] = $row_user;
foreach ($allevents as $val) {
$eventID = $val['event_ID'];
echo "<br>$eventID";
echo "End foreach.";
} // end foreach events as val
echo "End While.";
} // end while
print_r($allevents);
And get the following output:
Display events: (3)
ID 1 End foreach.End While.
ID 1 End foreach.
ID 2 End foreach.End While.
ID 1 End foreach.
ID 2 End foreach.
ID 3 End foreach.End While.
Array (
[0] => Arr开发者_JS百科ay (
[event_ID] => 1
[eventtype] => 1
[eventlocation] => 1
[eventhostfamily] => 23
[eventturn] => 459
[char1] => 9
[char2] => 19
)
[1] => Array (
[event_ID] => 2
[eventtype] => 4
[eventlocation] => 1
[eventhostfamily] => 29
[eventturn] => 461
[char1] => 208
[char2] => 0
)
[2] => Array (
[event_ID] => 3
[eventtype] => 4
[eventlocation] => 1
[eventhostfamily] => 28
[eventturn] => 462
[char1] => 1
[char2] => 0
)
)
For some reason that I cannot fathom, its giving me some weird loop where it returns the 1st row, then the first two rows, then the first three rows.
What am I doing wrong?
You are appending each row from mysql to your array and then output the whole array. Move the foreach loop out of your while:
while ($row_user = mysql_fetch_assoc($result)){
$allevents[] = $row_user;
echo "End While.";
} // end while
foreach ($allevents as $val) {
$eventID = $val['event_ID'];
echo "<br>$eventID";
echo "End foreach.";
} // end foreach events as val
精彩评论