Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retrieving data and populating a combo box 1

Status
Not open for further replies.

IanNav

Programmer
Feb 26, 2001
79
Hi,

I’m sure this is simple one to most people, I just probably been thinking too hard... :)

problem : I have a mini CMS I’ve created. As usual i have an add, edit & remove screen for each item. (i.e. products).

how do I get a value from my MYSQL and auto select the right one in the combo box.

See Example.


Combo box contains the following options (hard coded):

"<please select>"
"Check availability"
"Confirmed"
"TBC"
"Cancelled"

I have done a mysql query and got the relevant info (stored in $data[status]).

how do I select the value from the list that matches my db data.

i.e., if $data[status] = TBC, how would I get the page to load with TBC selected.

I know I have to put "selected" next to the option but I can't get it to do it dynamically.

any help would be appreciated,

Many thanks

Ian



 
my suggestion is something like this:

Code:
$options = array("Check availability","Confirmed","TBC","Cancelled");

// the above array would probably be better populated by a call to the database to select all those strings out of some table, but, as you said, you currently are hard-coding the select box...

echo "<select name=\"myselect\"><option value=\"\"> -please select- </option>";

foreach ($options as $option) {
    echo "<option value=\"".$option."\"";
    if ($option == $data["status"]) echo " SELECTED";
    echo ">".$option."</option>";
}
echo "</select>";

The basic idea here is to use PHP to dynamically write to the output stream (the HTML) the contents of the select box one by one. as you go through the loop, the if-statment checks each option to see if it should include in the output the "SELECTED" tag. once the final HTML is composed and sent to the browser, it will know which option to have selected based on the HTML you sent it. happy coding!
 
Thanks shadedecho!

Perfect, works really well...

i didn't know about te foreach loop... i do now.

Regards,

Ian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top