已在页面加载中选择的选项在下拉列表中也可以更改 [英] an option already selected on page load in drop down list and also changeble

查看:64
本文介绍了已在页面加载中选择的选项在下拉列表中也可以更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

PHP - 预先选择下拉选项

我的php项目中有一个用户可以编辑他的帐户的情况。

I have a situation in my php project where a user can edit his account.

在编辑中,有一个城市字段,它是城市的下拉列表。

In editing, there is a city field which is a drop down list of cities.

我想在编辑前选择一个在个人资料中的城市(用户在注册时输入的城市)。

I want to already select one city which is in profile before editing(the one which user enter at the time of registration).

他也可以通过选择前面的下拉列表来改变他的城市。

Also he is able to change his city by choosing fron drop down list.

Html代码:

<div class="search_bar1_txt">State:</div>
<div class="search_bar1">
<select class="styled" name="state_trainer">
 <option>-select-</option>
 <option>washington</option>
 <option>perth</option>
 <option>delhi</option>
 <option>london</option>
 </select></div>
</div>

编辑时我正在使用此代码获取用户的当前数据(城市):

on editing I am using this code to fetch current data(city) of user:

<?php
if(isset($_GET['userid']))
{
$sql = "select city from `wp_pelleresuser` where userId =".$_GET['userid'];
$result = mysql_query($sql);
$value = mysql_fetch_assoc($result);
}?>

请告诉我如何从数据库中获取一个选项。

please tell me how can I get already selected one option which is fetch from database.

而且它也是可以改变的。

And also it is changeable.

推荐答案

你可以做到在许多方面,最简单的(也可能是最不优雅的)是做这样的事情:

You can do it in a number of ways, the simplest (and probably least elegant) is to do something like this:

<select class="styled" name="state_trainer">
<?php
$myCity='london'; // assumed to be data from database...
echo '<option'.($myCity=='-select-') ? ' selected ' : ' ' .'-select-</option>';
echo '<option'.($myCity=='washington') ? ' selected ' : ' ' .'washington</option>';
?>

这当然很可怕。

我建议您在将数据从数据库中提取出来并将初始下拉列表放在一起时检查数据。

I would rather suggest that you check the data as you are pulling your information out of the database and putting your initial dropdown list together.

如果要创建数据数组创建下拉列表(例如)在那里检查它然后。如果城市符合您的要求,请立即在您的循环中进行。

If you are making an array of data to create the drop down list (for example) check it right there and then. If the city matches what you want, do it inside your loop right off the bat.

$usersCity="london";
$myCityList=array();

while( ... ) // Database loop that is pulling the data from the database.
{
    $selected='';
    if($userCity==$row['city'])
    {
        $selected=' selected ';
    }
    $myCityList[]='<option'.$selected.'>'.$row['city'].'</option>';
}

然后要显示下拉列表,您可以这样做:

Then to display the drop down list, you can simply do this:

$cityCount=count($myCityList);
for($i=0;$i<$cityCount;$i++)
{
    echo $myCityList[$i].'\n';
}

用户城市已被选中。

这篇关于已在页面加载中选择的选项在下拉列表中也可以更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆