1

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

    ...

}

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.