Populating a combo box

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Populating a combo box

Post 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
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

Thanks a lot for your very prompt reply.

I'll give it a go.

Cheers.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
Post Reply