Enjoy unlimited access to all forum features for FREE! Optional upgrade available for extra perks.
NDD Camp 2024

PHP/MySQL setting selected option for Dropdown Menu

Status
Not open for further replies.

MrDude

Level 8
Legacy Platinum Member
Joined
Jun 10, 2005
Messages
1,219
Reaction score
1
I always see it on forums and stuff, when you go to edit your profile, your date of birth or whatever you put in a dropdown menu is shown to you, exactly how you selected it.

I have a form where people enter their date of birth, location etc, and I want it so when they go to edit, they see their selections already selected in the dropdown list by adding selected='selected' to it, I really cant figure out how to do it, and my only workaround right now is to add a duplicate at the top of the dropdown list.
 

katherine

Country hopper
Legacy Exclusive Member
Joined
Jul 9, 2005
Messages
8,428
Reaction score
1,290
Here is one example.

The idea is that when the form loads, you retrieve their saved data from the DB. Let's just fetch their year of birth as an example.
Then you build your combo using a loop (here current year = 2009 through 1909). The year that matches your variable gets the selected attribute.

PHP:
<?php
$link=mysql_pconnect("localhost","user","password");
mysql_select_db("db",$link);
$result = mysql_query("select date_format(birth_date,'%Y') as birth_year from members where member_id=1");

$row=mysql_fetch_array($result); // fetch first row
$year=$row["birth_year"]; // retrieve 4-digit year of birth

// display combo: current year -> -100
$current_year=date("Y");
echo '<select name="cbo_year">';
for ($i = $current_year; $i >= ($current_year-100); $i--) {
echo '<option '.($year == $i ? ' selected ' : '').' value="'.$i.'" >'.$i.'</option>';
}
echo '</select>';
?>

For XHTML compliant code use this instead
PHP:
echo '<option '.($year == $i ? ' selected="selected " ' : '').' value="'.$i.'" >'.$i.'</option>';
 

MrDude

Level 8
Legacy Platinum Member
Joined
Jun 10, 2005
Messages
1,219
Reaction score
1
Thankyou!

That was exactly what I was looking for with regards to their date of birth, but my biggest pain is Location of the users, with a long dropdown list is there an easy way about it? Its not really important, im just looking to have things working properly, if its too much hassle for me I may just duplicate their location such as "United States" at the top of the list.
 
Status
Not open for further replies.

The Rule #1

Do not insult any other member. Be polite and do business. Thank you!

Sedo - it.com Premiums

IT.com

Premium Members

AucDom
UKBackorder
Be a Squirrel
MariaBuy

Our Mods' Businesses

URL Shortener
UrlPick.com

*the exceptional businesses of our esteemed moderators

Top Bottom