Page 1 of 1
Populating a combo box
Posted: Thu Mar 02, 2006 7:47 am
by aceconcepts
Hi,
I'm using PHP with MySql. How can i populate a combo/drop-down box with data from a table stored in a MySql db?
Thanks.
Nick
Posted: Thu Mar 02, 2006 7:51 am
by shiznatix
Code: Select all
//assuming you have already done the query
echo '<select name="awesome">';
while ($info = mysql_fetch_assoc($query))
{
echo '<option value="'.$info['yourFieldName'].'">'.$info['anotherFieldName'].'</option>';
}
echo '</select>';
same idea for the other thing
Posted: Thu Mar 02, 2006 7:53 am
by aceconcepts
Thanks a lot for your very prompt reply.
I'll give it a go.
Cheers.
Posted: Thu Mar 02, 2006 11:36 am
by John Cartwright
Code: Select all
echo '<select name="awesome">';
while ($info = mysql_fetch_assoc($query))
{
echo '<option value="'.$info['yourFieldName'].'"'. (!empty($_POST['awesome']) && $_POST['awesome'] == $info['yourFieldName'] ? ' selected=selected' : '').'>'.$info['anotherFieldName'].'</option>';
}
echo '</select>';
One feature that is commonly added is to default to the selected form, in case there was a form error where you have to ask your user to enter missing fields. This way, they won't have to select the select box again