Using datbase in a <select>

A

Anonymous

Guest
How can I use information stored in data fields of a table in a MySQL database as the options in <select>?
In other words, I need to have a dynamic option list determined by the data elements in a database.
Thanks
 
Code:
<?php

#connect to the database first then do the following:
$result = mysql_query("SELECT * FROM table");
$select = "<select name='myselect'>";
while($row = mysql_fetch_assoc($result)){
   $select.="<option value='".$row['value']."'>".$row['name']."</option>";
}
$select .="</select>";

echo($select);
?>

That will do the trick..
NOTE: this topic is moved to mysql and PHP coding..
 
Thanks. This worked great. :)
If you don't mind I have another question in this subject.
How can I default to a value in a <select>? Let's say I want to show them the original value of the variable and then let them pick any other value from the option list if they want to.
Thanks.
 
just adding selected to the options part:

<option value="" selected>something</option>

you may want to make a function that will populate the dropbox and pass a value of the option that should be selected as an argument to that function.. then in a while loop check the value of the row and the value of the variable that has been passed to the function.. if they are alike: add selected to that option..
 
Once again; your comments were very helpful and it worked great.
I will follow your instruction to create a function to dynamically check for selected items in the drop off list.

Thanks
 
Back
Top