combo box + database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jiggajames
Forum Newbie
Posts: 3
Joined: Thu Aug 04, 2005 8:39 pm

combo box + database

Post 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
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post 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.
Sander
Forum Commoner
Posts: 38
Joined: Sat Aug 06, 2005 12:43 pm

Post 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.
User avatar
Ashiro
Forum Newbie
Posts: 8
Joined: Wed Jun 22, 2005 5:01 am
Contact:

Post 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.
Post Reply