Forum Moderators: coopster

Message Too Old, No Replies

Using database to populate drop down menu.

         

mgworek

5:27 pm on May 31, 2006 (gmt 0)

10+ Year Member



I have it working cept for when there is a error in the form and it repopulates the fields in the form, I am having trouble getting the drop down to work.

just for testing, i used this code...

print "<option value='$row[state_name]'>$row[state_name]</option>";
print "<option value='$state' selected='selected'>$state</option>";

which lists all the states in the database but then lists the selected state after each state in the database.

any suggestions on where to look?

This is my code for the lookup...

<?
$result = mysql_query("SELECT * FROM `states`") or die(mysql_error());
echo "<select name='state'>";
while($row = mysql_fetch_assoc($result)) {
echo "<option value='$row[state_name]'>$row[state_name]";
}
echo "</select>";
?>

coopster

6:24 pm on May 31, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You just need to break up your options a bit and append when the selection has been made ...
<? 
$result = mysql_query("SELECT * FROM `states`") or die(mysql_error());
echo "<select name='state'>";
while($row = mysql_fetch_assoc($result)) {
echo "<option value='$row[state_name]'";
if (previously selected option == $row['state_name']) {
echo " selected='selected'";
}
echo ">$row[state_name]";
}
echo "</select>";
?>

mgworek

8:14 pm on May 31, 2006 (gmt 0)

10+ Year Member



thanx!

I was thinking there must be a way to use if selected value = something in the database but i was having trouble piecing it together!

coopster

8:46 pm on May 31, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You are welcome. I'm guessing the previously selected option is going to be that of your select box, 'state'. So, the code logic there is likely something such as
if (isset($_POST['state']) && $_POST['state'] == $row['state_name']) {  
echo " selected='selected'";
}