Jump to content

select option pre-filled from mysql database


brem13

Recommended Posts

hey, i have a profile page with options to edit, and i was wondering how i would go about having the options pre-selected if they are already in a mysql database?

<select name="hair">
	<option name="brown">Brown</option>
	<option name="blonde" selected>Blonde</option>
	<option name="black">Black</option>
	<option name="red">Red</option>
	<option name="brunette">Brunette</option>
	<option name="auburn">Auburn</option>
	<option name="gray">Gray</option>
	<option name="white">White</option>
	<option name="other">Other</option>
	<option name=""></option>
</select>

like if someone already filled out the profile page and their hair color was gray, how would i have it automatically go to that in the drop down????

 

here is the mysql code

mysql_connect($server, $db_user, $db_pass) or die (mysql_error()); 
$result = mysql_db_query($database, "select * from $table WHERE email = '$email'") or die (mysql_error());
while($qry = mysql_fetch_array($result)){ 
	$gender = $qry['hair'];
}//end while

 

I would setup up an array of all hair colors, eg

$hair_colors = array('brown', 'blonde', 'black', 'red', 'brunette', etc etc);

 

I'd then use a foreach loop to dynamically generate the drop down menu and have a condition inside to it which compares the current color with that in the database. If there is a match add selected="selected" to the <option> tag.

echo '<select name="hair_color">';
foreach($hair_colors as $color)
{
    $selected = (($color == $qry['hair']) ? ' selected="selected"' : '');
    echo '<option value="'.$color.'"'.$selected.'>'.$color.'</option>';
}
echo '</select>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.