Using PHP to populate a dropdown? [duplicate]

What about something like this :

echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
    echo '<option value="' . htmlspecialchars($row['column_for_value']) . '">' 
        . htmlspecialchars($row['column_for_label']) 
        . '</option>';
}
echo '</select>';

Of course, up to you to decide which items from $row should be used for the value and the text of each <option>

Just make sure you are escaping the data that comes from your DB — especially if it can contain HTML ; as you are outputting HTML, this can be done with htmlspecialchars or htmlentities.

Note that those might take a couple of additionnal parameters that I didn’t use in my example — setting those can be useful, depending on the charset you’re using.

Leave a Comment

tech