/    Sign up×
Community /Pin to ProfileBookmark

Dynamic Dropdown Menu with MySQL Database

OK folks. Here it is.

In the ‘Profile’ section of my web site, I am storing the ‘country’ of each user, they select it and submit it to the database. It gets stored there, so when they return to the ‘edit_profile’ file they have that country as the default.

This is what I want to happen. However, this is not happening.

For example, I have the following code :

[code] <select name=”country” size=”1″>’;
if ($country == “Afghanistain”) {
echo ‘<option value=”Afghanistain” selected>Afghanistain</option>’;
} else {
echo ‘<option value=”Afghanistain”>Afghanistain</option>’;
}
if ($country == “Albania”) {
echo ‘<option value=”Albania” selected>Albania</option>’;
} else {
echo ‘<option value=”Albania”>Albania</option>’;
}’;</select></p>[/code]

But it doesn’t like it ? It doesn’t store and KEEP the country selected in the profile.

Please help out if you can.

to post a comment
PHP

9 Comments(s)

Copy linkTweet thisAlerts:
@bokehJan 26.2006 — Post the whole thing... and this time use the php code tags. (button marked php).
Copy linkTweet thisAlerts:
@invisionauthorJan 26.2006 — [code=php]<?php # this file allows a user to edit a users details.

// This page edits a user.

$page_title = "Edit your own Profile";
include ('./includes/header.html');

require_once ('../mysql_connect.php'); // Connect to the db.

$id = $_SESSION['user_id'];

// Checks if the form has been submitted.
if (isset($_POST['submitted'])) {

if (eregi ('^[[:alpha:].' -]{2,15}$', stripslashes(trim($_POST['nickname'])))) {
$nick = escape_data($_POST['nickname']);
} else {
$nick = FALSE;
echo '<p><font color="red" size="+1">Please enter a valid nick name(only letters).</font></p>';
}

// Check for age between 1 and 120.
if (eregi ('[0-9]', stripslashes(trim($_POST['age'])))) {
$age = escape_data($_POST['age']);
} else {
$age = FALSE;
echo '<p><font color="red" size="+1">Please enter a valid age.</font></p>';
}

if (!isset($_POST['sex'])) {
die('You must select your gender');
}

if (!isset($_POST['maillist'])) {
die('Please select whether you wish to subscribe to the mailing list');
}

if ($nick && $age) { // If all of these variables(everything) are A-OK.

// Make the Query to edit the user using UPDATE

$query = "UPDATE profiles SET nickname='$nick', sex='$sex', age='$age', interests='$interest', country='$country', maillist='$maillist' WHERE user_id=$id";
$result = @mysql_query ($query); // Run the Query
if (mysql_affected_rows() == 1) { // If it ran OK and one row was affected.

// Print a message
echo '<H2>Edit your Profile</H2>
<P>Your profile has been edited</p><p><br /><br /></p>';

// Finish the page
echo '<H3>Thank you for adding your own profile to Pictures of Scotland! To edit this profile or delete your own profile, simply return to the Edit Profile page.</h3>';
include ('./includes/footer.html'); // Include the HTML footer.
exit();

} else { // No changes made
echo '<p><font color="red" size="2">No changes have been made to your profile.</font></p>';
}
} else { // RE Error
echo '<p><font color="red" size="+1">Please make sure you have used only letters or numbers in the appropriate fields.</font></p>';
}



} // End of the main Submit conditional.

// Always show the form.

// Retrieve the user's information.

$query = "SELECT nickname, sex, age, interests, country, maillist FROM profiles WHERE user_id=$id";
$result = mysql_query($query); // Run the Query.

if (mysql_num_rows($result) == 1) { // Valid user ID, show the form.

// Get the user's information.
$row = mysql_fetch_array($result, MYSQL_NUM);

// Create the form.
echo '<h3>Edit a User</h3>
<form action="edit_profile.php" method="post">
<p><b>Nick Name:</b> <input type="text" name="nickname" size="15" maxlength="15" value="' . $row[0] . '" /></p>
<input type="radio" name="sex" value="M"'.(('M' == @$row[1])?' checked="checked"':'').' />male<br>
<input type="radio" name="sex" value="F"'.(('F' == @$row[1])?' checked="checked"':'').' />female<br>
<p><b>Age:</b> <input type="text" name="age" size="3" maxlength="3" value="' . $row[2] . '" /></p>
<p><b>Interests:</b> <textarea rows="5" cols="40" name="interest">' . $row[3] . '</textarea><small>(optional)</small></p>
<p><b>Country:</b>
<select name="country" size="1">';
if ($country == "Afghanistain") {
echo '<option value="Afghanistain" selected>Afghanistain</option>';
} else {
echo '<option value="Afghanistain">Afghanistain</option>';
}
if ($country == "Albania") {
echo '<option value="Albania" selected>Albania</option>';
} else {
echo '<option value="Albania">Albania</option>';
}
'</select></p>

<input type="radio" name="maillist" value="Y"'.(('Y' == @$row[5])?' checked="checked"':'').' />Subscribe<br>
<input type="radio" name="maillist" value="N"'.(('N' == @$row[5])?' checked="checked"':'').' />Unsubscribe<br><input type="submit" name="submit" value="Edit Profile" />
<input type="hidden" name="submitted" value="TRUE" />
</form>';

} else { // Not a valid User ID.
echo '<h2>Page Error</h2>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}

mysql_close(); // Close connection with db.

include ('./includes/footer.html'); // Include the HTML footer.
?>
[/code]


sql :

<i>
</i>CREATE TABLE <span><code>profiles</code></span> (
<span><code>pid</code></span> tinyint(4) NOT NULL auto_increment,
<span><code>nickname</code></span> varchar(15) NOT NULL default '',
<span><code>sex</code></span> enum('M','F') NOT NULL default 'M',
<span><code>age</code></span> tinyint(3) NOT NULL default '0',
<span><code>interests</code></span> text NOT NULL,
<span><code>country</code></span> varchar(50) NOT NULL default '',
<span><code>maillist</code></span> enum('Y','N') NOT NULL default 'Y',
<span><code>user_id</code></span> tinyint(4) NOT NULL default '0',
PRIMARY KEY (<span><code>pid</code></span>)
)
Copy linkTweet thisAlerts:
@JanSeppJan 26.2006 — Here's what I used in a similar case:

$query = "SELECT countryAbbreviation, countryDescription from tblCountries";

$result = mysql_query($query);

while ( $countryRow = mysql_fetch_array($result, MYSQL_ASSOC) )

{

if ( $countryRow[countryAbbreviation] == $userData[country] ) {

print "<option value="$countryRow[countryAbbreviation]" selected >$countryRow[countryDescription]</option>n";

}

else {

print "<option value="$countryRow[countryAbbreviation]">$countryRow[countryDescription]</option>n";

} // end-if ( $countryRow[coun ...

} // end-while ( $countryRow = ...

HtH,

Jan
Copy linkTweet thisAlerts:
@bokehJan 26.2006 — Are those the only countries on the list or have you shortened the list?
Copy linkTweet thisAlerts:
@invisionauthorJan 26.2006 — Thanks for the reply.

So should I have a table in my database for strictly storing countries ?
Copy linkTweet thisAlerts:
@invisionauthorJan 26.2006 — I've just shortened the list for now ?
Copy linkTweet thisAlerts:
@bokehJan 26.2006 — In this example I have used an arrary for countries but you can do what you like with them. [B]Following not tested.[/B] [code=php]<?php # this file allows a user to edit a users details.

// This page edits a user.

$page_title = "Edit your own Profile";
include ('./includes/header.html');

require_once ('../mysql_connect.php'); // Connect to the db.

$id = $_SESSION['user_id'];

// Checks if the form has been submitted.
if (isset($_POST['submitted'])) {

if (eregi ('^[[:alpha:].' -]{2,15}$', stripslashes(trim($_POST['nickname'])))) {
$nick = escape_data($_POST['nickname']);
} else {
$nick = FALSE;
echo '<p><font color="red" size="+1">Please enter a valid nick name(only letters).</font></p>';
}

// Check for age between 1 and 120.
if (eregi ('[0-9]', stripslashes(trim($_POST['age'])))) {
$age = escape_data($_POST['age']);
} else {
$age = FALSE;
echo '<p><font color="red" size="+1">Please enter a valid age.</font></p>';
}

if (!isset($_POST['sex'])) {
die('You must select your gender');
}

if (!isset($_POST['maillist'])) {
die('Please select whether you wish to subscribe to the mailing list');
}

if ($nick && $age) { // If all of these variables(everything) are A-OK.

// Make the Query to edit the user using UPDATE

$query = "UPDATE profiles SET nickname='$nick', sex='$sex', age='$age', interests='$interest', country='$country', maillist='$maillist' WHERE user_id=$id";
$result = @mysql_query ($query); // Run the Query
if (mysql_affected_rows() == 1) { // If it ran OK and one row was affected.

// Print a message
echo '<H2>Edit your Profile</H2>
<P>Your profile has been edited</p><p><br /><br /></p>';

// Finish the page
echo '<H3>Thank you for adding your own profile to Pictures of Scotland! To edit this profile or delete your own profile, simply return to the Edit Profile page.</h3>';
include ('./includes/footer.html'); // Include the HTML footer.
exit();

} else { // No changes made
echo '<p><font color="red" size="2">No changes have been made to your profile.</font></p>';
}
} else { // RE Error
echo '<p><font color="red" size="+1">Please make sure you have used only letters or numbers in the appropriate fields.</font></p>';
}



} // End of the main Submit conditional.

// Always show the form.

// Retrieve the user's information.

$query = "SELECT nickname, sex, age, interests, country, maillist FROM profiles WHERE user_id=$id";
$result = mysql_query($query); // Run the Query.

if (mysql_num_rows($result) == 1) { // Valid user ID, show the form.

// Get the user's information.
$row = mysql_fetch_array($result, MYSQL_NUM);

// Create the form.
echo '<h3>Edit a User</h3>
<form action="edit_profile.php" method="post">
<p><b>Nick Name:</b> <input type="text" name="nickname" size="15" maxlength="15" value="' . $row[0] . '" /></p>
<input type="radio" name="sex" value="M"'.(('M' == @$row[1])?' checked="checked"':'').' />male<br>
<input type="radio" name="sex" value="F"'.(('F' == @$row[1])?' checked="checked"':'').' />female<br>
<p><b>Age:</b> <input type="text" name="age" size="3" maxlength="3" value="' . $row[2] . '" /></p>
<p><b>Interests:</b> <textarea rows="5" cols="40" name="interest">' . $row[3] . '</textarea><small>(optional)</small></p>
<p><b>Country:</b>
<select name="country" size="1">
<option></option>'."n";

$countries = array('Afghanistan', 'Albania', 'Algeria', 'American samoa', 'Andorra', 'Angola', 'Antarctica',
'Antigua and barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan',
'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin',
'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia and herzegovina', 'Botswana', 'Brazil',
'British indian ocean territory', 'Brunei darussalam', 'Bulgaria', 'Burundi', 'Cambodia',
'Cameroon', 'Canada', 'Cape verde', 'Cayman islands', 'Central african republic', 'Chad',
'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Cook islands', 'Costa rica', 'Cote d'ivoire',
'Croatia', 'Cuba', 'Cyprus', 'Czech republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican republic',
'Ecuador', 'Egypt', 'El salvador', 'Equatorial guinea', 'Eritrea', 'Estonia', 'Ethiopia',
'Falkland islands (malvinas)', 'Faroe islands', 'Federated states of micronesia', 'Fiji',
'Finland', 'France', 'French guiana', 'French polynesia', 'French southern territories',
'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland',
'Grenada', 'Guadeloupe', 'Guam', 'Guatemala', 'Guinea', 'Guinea-bissau', 'Guyana', 'Haiti',
'Holy see (vatican city state)', 'Honduras', 'Hong kong', 'Hungary', 'Iceland', 'India',
'Indonesia', 'Iraq', 'Ireland', 'Islamic republic of iran', 'Israel', 'Italy', 'Jamaica',
'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Kuwait', 'Kyrgyzstan',
'Lao people's democratic republic', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia',
'Libyan arab jamahiriya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Madagascar',
'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall islands', 'Martinique',
'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Monaco', 'Mongolia', 'Morocco', 'Mozambique',
'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'Netherlands antilles', 'New caledonia',
'New zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norfolk island', 'Northern mariana islands',
'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestinian territory, occupied', 'Panama', 'Papua new guinea',
'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Puerto rico', 'Qatar', 'Republic of korea',
'Republic of moldova', 'Reunion', 'Romania', 'Russian federation', 'Rwanda', 'Saint kitts and nevis',
'Saint lucia', 'Saint vincent and the grenadines', 'Samoa', 'San marino', 'Sao tome and principe',
'Saudi arabia', 'Senegal', 'Serbia and montenegro', 'Seychelles', 'Sierra leone', 'Singapore',
'Slovakia', 'Slovenia', 'Solomon islands', 'Somalia', 'South africa', 'Spain', 'Sri lanka',
'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syrian arab republic', 'Taiwan',
'Tajikistan', 'Thailand', 'The democratic republic of the congo', 'Macedonia', 'Timor-leste',
'Togo', 'Tokelau', 'Tonga', 'Trinidad and tobago', 'Tunisia', 'Turkey', 'Turkmenistan',
'Tuvalu', 'Uganda', 'Ukraine', 'United arab emirates', 'United kingdom', 'Tanzania',
'United states', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Viet nam', 'Virgin islands, british',
'Virgin islands, u.s.', 'Yemen', 'Zambia', 'Zimbabwe');

for($i = 0, $j = count($countries); $i < $j; $i++){
echo '<option value="'.$countries[$i].'"'.(($countries[$i] == @$row[4])?' selected="selected"':'').'>'.$countries[$i].'</option>'."n";
}
echo ' </select></p>

<input type="radio" name="maillist" value="Y"'.(('Y' == @$row[5])?' checked="checked"':'').' />Subscribe<br>
<input type="radio" name="maillist" value="N"'.(('N' == @$row[5])?' checked="checked"':'').' />Unsubscribe<br><input type="submit" name="submit" value="Edit Profile" />
<input type="hidden" name="submitted" value="TRUE" />
</form>';

} else { // Not a valid User ID.
echo '<h2>Page Error</h2>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}

mysql_close(); // Close connection with db.

include ('./includes/footer.html'); // Include the HTML footer.
?>[/code]
Copy linkTweet thisAlerts:
@invisionauthorJan 26.2006 — I'll seriously need to consider paying you for your absolute genious bokeh.

It works!

I'm now a very happy man. Thanks for your patience and thought you put into helping me out, you're a gem!
Copy linkTweet thisAlerts:
@bokehJan 26.2006 — I've never heard of a happy Scotsman before ?
×

Success!

Help @invision spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...