Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ){

    ...

}
share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

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;
share|improve this answer
    
+1 I was about to post the same :) –  Shehi Feb 28 '11 at 21:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.