可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have created a profile page in php where a user using an html drop down list chooses gender.
The html code is the following:
Gender<select name="gender"> <option value=" "> EMPTY </option> <option value="Male">Male</option> <option value="Female">Female</option> </select>
After the user chooses gender the form dispatches and saves the data into database. All I want is that the next time that the user visits the profile page, the drop down list to keep the value that the user selected before. For example if user selected in drop down list "male", next time he visited profile page to make changes, the drop down list must show "male" as selected value(keeping it from previous time). Any idea how to do this in PHP?
回答1:
What you need to do is give the selected
attribute to the option. Assuming you store profile information on the session and have short-tags enabled on your server, you can do something like this:
Gender: <select name="gender"> <option value=" "> Not Selected </option> <option value="Male"<?=$_SESSION['gender'] == "Male" ? ' selected="selected"' : ''?>>Male</option> <option value="Female"<?=$_SESSION['gender'] == "Female" ? ' selected="selected"' : ''?>>Female</option> </select>
回答2:
There is a pretty simplistic way to do this if you are using a form. Also, you probably want to use isset() in case it is the first time they visited the page.
<select name="gender"> <option value="male" <?php echo isset($_GET["gender"]) && $_GET["gender"] == "male" ? "selected" : "" ?>>Male</option> <option value="female" <?php echo isset($_GET["gender"]) && $_GET["gender"] == "female" ? "selected" : "" ?>>Female</option> </select>
All this does is insert "selected" into the option tag if the $_GET variable is set and the last one was that specific option. Hope this helps!
回答3:
You must read the database and add a php script like:
<option value="Male" <?php if ($gender == "Male") { echo " selected"; } ?>>Male</option> <option value="Female" <?php if ($gender == "Female") { echo " selected"; } ?>>Female</option>