Forum Moderators: coopster

Message Too Old, No Replies

Retrieving data from a database into a <select> field

The data goes into the database, but it doesn't come out...

         

Soynogg

4:42 pm on Jun 27, 2005 (gmt 0)

10+ Year Member



Hello, all

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!

sned

4:54 pm on Jun 27, 2005 (gmt 0)

10+ Year Member



Hi Soynogg ... welcome to Webmasterworld!

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

Soynogg

5:27 pm on Jun 27, 2005 (gmt 0)

10+ Year Member



It does help, actually... I thought looping through an array could be a solution, but I wasn't sure how to implement it. Thanks!