Forum Moderators: coopster
I'm writing a handfull of forms to enter data into a MySQL database, and then retrieve the data for editing. The form works fine when retrieving data into text boxes with
<input type=text value="<? echo $varname?>">
and with checkboxes by using
<input type="checkbox" <? if (isset($varname)) {echo "checked";}?>
My problem is that I can't use the above techniques to retrieve data from <select> lists. When I bring the edit form up, it returns the list's default value, and the default value is saved on the database unless the user changes the <select> field everytime the form is open.
I guess my question is simpler than I make it sound: how do I update a <select> field to display the value stored in the database?
Thanks a bunch!
To have a select option come up selected, you need to add
selected="selected" to the option:
<select name="somename">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected="selected">Three</option>
</select>
This would mean that option 3 would be selected when the page loaded.
So, to select the value from the database, your select options could be in an array:
$options = array('One','Two','Three'); etc
Then loop through the array:
foreach($options as $id=>$value){
// Check to see if the database value is equal to the array id
$seltext = ($row->somevalue == $id)? selected="selected"' : '';
echo "<option value=\"$id\" $seltext>$value</option>";
}
I hope that explains it well enough ...
-sned