Page 1 of 1

looping through a db and putting some info into array

Posted: Mon Apr 21, 2003 3:54 pm
by toms100
i have a database called buildings with amongst other things, 3 important things:
xcord << x cooridinate
ycord << y cooridinate
status << either SOLD, forsale, or forrent

ive done my sql query and have a variable called $buildings with the entire result in.
what i would like to do is creat an array, ie:
$location[Xcord][Ycord] = status

but i cant work out the best way to get the information from the database and put it in this array.
i think will will probably have to use two nested foreach statments, but im not sure :/

hope someone can help

Tom

Posted: Tue Apr 22, 2003 7:02 am
by McGruff
If you have a column like building name - or the old favourite auto-incrementing integer ID column (which I've called bid here):

Code: Select all

<?php

$mysql = "SELECT bid, xcord, ycord, status FROM table_name";
$query = mysql_query($mysql) or die("Cannot query the database.<br>" . mysql_error());

while($result = mysql_fetch_array($query)) {
    $bid = $result['bid'];
    $location[$bid]['xcord'] = $result['xcord'];
    $location[$bid]['ycord'] = $result['ycord'];
    $location[$bid]['status'] = $result['status'];
    unset($bid); 
}

?>
The unset() line won't be needed with an auto-incrementing integer column but if you use a "name" column, and a record doesn't have a name for some reason, the next loop would overwrite the previous one. Basically, the first key has to relate to a column which always has a value and the value is unique.

In a sense, the multi dimensional array $location is merely duplicating the $query resource: perhaps you need it for something - if not work with $query directly.