简体   繁体   中英

MySQL-SELECT into special array

i want to get an array like this:

$autocompletiondata = array(
    3 => 'Hazel Grouse',
    4 => 'Common Quail',
    5 => 'Common Pheasant',
    6 => 'Northern Shoveler',
    7 => 'Greylag Goose',
    8 => 'Barnacle Goose');

out off this SQL-Query:

SELECT id, name FROM tbl_1

Can anyone tell me how to do this?

$autocompletiondata = array();

$sql = "SELECT id, name FROM tbl_1";
$result = mysql_query($sql) or die(mysql_error());

while($row = mysql_fetch_assoc($result)) {
   $autocompletiondata[$row['id']] = $row['name'];
}

This presumes that you've established a connection to the database, etc...

$autocompletiondata =  array(); 

$query  = "SELECT id, name FROM tbl_1";           
$result = mysql_query($query) or die(mysql_error());

while(list($id, $name) = mysql_fetch_array($result))
{
$autocompletiondata[$id] = $name; 
}

easier to read:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM