Click to See Complete Forum and Search --> : foreach problems


lting
10-21-2004, 01:21 AM
$data = array('1', '2', '3');

foreach($data as $key){
echo $key;
}

this give me result 1,2,3

i got one table (items) in database with one column ('itemid') and there are 4 results inside the table (1,2,3,4)

i want to use foreach to display the results in my database.. so i do

$query = select itemid from items;
$result = mysql_query($query);

$array = mysql_fetch_array($result);

foreach($array as $data){
echo $data;
}

why it is not working? cos $array is an array already? can anyone guide me here :( sorry newbie here

HaganeNoKokoro
10-21-2004, 01:36 AM
mysql_fetch_array fetches one row from the database table (in your case, one column). Since you said$array = mysql_fetch_array($result);$array will be the same as if you had coded this:$array[0]=1;
$array['itemid']=1;To go through all the rows of a query, you need something more like this$query = select itemid from items;
$result = mysql_query($query);
while($array = mysql_fetch_array($result)) {
echo $array[0];
//you could get the same result with echo $array['itemid'];
}In this case, you have not specified the array indexing type in the mysql_fetch_array, so it will give you both numerical indexes and associative (string) indexes. See http://ca.php.net/manual/en/function.mysql-fetch-array.php for more info.