Page 1 of 1

combo box + database

Posted: Mon Aug 08, 2005 1:41 pm
by jiggajames
Alright so I have a website where people can create and edit profiles. One of the fields on their profile is state. All the info is stored as a row in a mysql database. When someone edits their profile they get a form with all their current information already filled in. However I can't figure out how to make the combo box have the persons current state selection selected as default. Does anyone know how to do this?

thanks,
james

Posted: Mon Aug 08, 2005 1:46 pm
by neophyte

Code: Select all

<option name="state" value="MA" selected><option>
You've got to have selected at the end of the tag.

How do you get it there? Well it depends on you PHP code.

Posted: Mon Aug 08, 2005 1:47 pm
by Sander
Create the HTML of the combobox in a loop (Each time you move through the loop, you add something else to the combobox. You could just store all the options in an array and move through that array). Inside that loop, just check the value you're about to insert to see if it's the same as the user's current selection. If it's the same, add " selected='selected' " to the option.

Posted: Mon Aug 08, 2005 1:47 pm
by Ashiro
You can use the following template I often find useful. It has some example data in it. As you can see the selected option needs to be the first placed into the selection. This data can come from a database source rather than manual entered as it is here.

Code: Select all

<?php 

function mkSelect($name, $nopt, $options, $default) { 
select name="".$name."\">\n"; 
        list($defkey,$defval) = each($default); 
        $out .= "<option value=\"".$defkey."\" selected>".$defval."</option>\n"; 
        while (list($key,$val) = each($options)) { 
                if ($key != $defkey) 
                        $out .= "<option value=\"".$key."\">".$val."</option>\n"; 
        } 
        $out .= "</select>\n"; 
        return $out; 
} 


$name = 'testSelect'; 
$options[1] = 'chicken'; 
$options[2] = 'monkey'; 
$options[3] = 'cow'; 

$default[0] = 'null'; 

$htmlSelect = mkSelect($name,'', $options, $default); 

?>
This bit appears at the top of the selection:

Code: Select all

$out .= "<option value=\"".$defkey."\" selected>".$defval."</option>\n";
Notice its called default.