foreach function to create array from mysql db
need to return an array like this for example:
array(30 => 'Mercedes Benz 310 ',26 => 'Lamborghini Murcielago')
I have a database set up something like this:
CREATE TABLE cars (
id bigint(20) NOT NULL auto_increment,
`car_name` tinyint(2) NOT NULL default '0',
owner varchar(20) NOT NULL default ''
PRIMARY KEY (id)
) ENGINE=MyISAM;
The id
need to be 开发者_开发技巧the array key
.
So I tried to use foreach
, but I have still not quite understood how it works.
$q = "select `id`, `car_name` from `cars` where `owner`='$username'";
$result = $conn->query($q);
unset($q);
if( !$result){
return array(0 => 'error');
}
$garage = $result->fetch_assoc();
$car_id = $garage["id"];
$car_name = $garage["car_name"];
foreach( $car_name as $key => $car_id ){
...
}
You aren't far off. Something like this should give you the kind of array you're looking for.
$q = "select `id`, `car_name` from `cars` where `owner`='$username'";
$result = $conn->query($q);
unset($q);
if( !$result){
return array(0 => 'error');
}
while($row = mysql_fetch_array($result)){
$garage[$row['id']] = $row['car_name'];
}
return $garage;
精彩评论