drop down list keep previous selected value in php

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!