Jump to content

Making an array out of a while statement


marcus

Recommended Posts

How would I make an array out of a while statement

[code]
$sql = "SELECT * FROM `list_items` WHERE `type` ='food'";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$row[item_id];
}
[/code]

and take the while statement stuff and put it into an array
Link to comment
https://forums.phpfreaks.com/topic/32341-making-an-array-out-of-a-while-statement/
Share on other sites

This will make an array called $array out of all the rows selected from your database.

[code=php:0]
$sql = "SELECT * FROM `list_items` WHERE `type` ='food'";
$res = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($res)) {
  $array[] = $row['item_id'];
}
[/code]

Then, to display this array you'll need a loop, something like.

[code=php:0]
foreach($array as $val) {
  echo $val;
}
[/code]

As you may have noticed, making an array out of a database record like you asked is next to useless. Its more work for both you and php to create two loops.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.