php - Display database table value in HTML dropdown <select> list -


apologies if similar question has been asked in past - did search previous questions had no luck finding answer needed.

i have account option on website 'my settings' area, allows users change details. 1 of details can change country. instead of allowing user type country (in html textbox), i've made things more restricted providing dropdown list of countries in world. i've briefed code below (as don't want paste list of countries , waste time):

<select name="country" id="country" class="required" value="<? echo $row_settings['country']; ?>"> <option value=""></option> <option value="afghanistan">afghanistan</option> <option value="albania">albania</option> ... <option value="uk">uk</option> <option value="usa">usa</option> ... </select> 

as 'my settings' area registered users, have database table - lets call 'users' , i'll use simplified version of it, have 'username' column , 'country' column. first row of data (i.e. first user's details) 'user1' (the username) , 'uk' (the country). you'll notice, 'user1' lives in 'uk' - data same 1 of dropdown list options (i.e. <option value="uk">uk</option> shown above).

when on 'my settings' page, have selected option 'uk' dropdown list, , clicked 'save' button (to update data 'user1' in table) - however, once page displays after clicking 'save' button, selected value is, you'll see above, first option value in dropdown list (i.e. <option value=""></option>). thing - data in table updated - if select 'usa' option on list, update 'country' data 'user1' 'usa'.

what i'm wanting is, user see country selected on list before clicking 'save' button - there reason why first option of dropdown list displays after form has been submitted , page reloads , displays? why happening? shouldn't table data 'country' column display (i.e. 'uk' option, selected in dropdown list before submitting form). yet if use html textbox country part of form, display table data 'country' column 'user1' row - i.e. display 'uk'.

sorry if part of question confusing or over-described, , many replies. if need, provide link page temporary login details can see i'm talking about.

here's quick poc you:

<?php $countries = ['afghanistan', 'albania', 'uk', 'usa']; $row_settings = [   'username' => 'joe',   'country' => 'uk' ] ?> <select name="country" type="text" id="country" class="required"> <?php foreach($countries $country): ?>   <option <?php echo ($row_settings['country'] == $country) ? 'selected' : ''; ?>><?php echo $country; ?></option> <?php endforeach; ?> </select> 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -