可能重复:
PHP-PRE选择下拉选项
在我的php项目中,用户可以编辑他的帐户。
在编辑中,有一个城市字段,它是城市的下拉列表。
我想在编辑之前已经选择一个在配置文件中的城市(用户在注册时输入的城市)。
此外,他还可以通过从下拉列表中选择来更改他的城市。
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>
在编辑时,我使用此代码来获取用户的当前数据(城市):
<?php
if(isset($_GET['userid']))
{
$sql = "select city from `wp_pelleresuser` where userId =".$_GET['userid'];
$result = mysql_query($sql);
$value = mysql_fetch_assoc($result);
}?>
请告诉我如何才能获得已经选择的一个选项,即从数据库中提取。
而且它是可变的。
<div class="search_bar1_txt">State:</div>
<div class="search_bar1">
<select class="styled" name="state_trainer">
<option <?if($value['city']=='-select-') echo "selected";?>>-select-</option>
<option <?if($value['city']=='washington') echo "selected";?>>washington</option>
<option <?if($value['city']=='perth') echo "selected";?>>perth</option>
<option <?if($value['city']=='delhi') echo "selected";?>>delhi</option>
<option <?if($value['city']=='london') echo "selected";?>>london</option>
</select>
</div>
</div>
您可以通过多种方式来实现,最简单(可能也是最不优雅的)就是这样做:
<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>';
?>
这当然很可怕。
我建议您在从数据库中提取信息并将初始下拉列表放在一起时检查数据。
如果你正在制作一个数据数组来创建下拉列表(例如),请立即检查它。如果这个城市符合你想要的,那就在你的圈子里马上做。
$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>';
}
然后要显示下拉列表,您可以简单地执行以下操作:
$cityCount=count($myCityList);
for($i=0;$i<$cityCount;$i++)
{
echo $myCityList[$i].''n';
}
将已经选择用户所在的城市。
我不确定这是否是一种清晰的方式,但你可以把代码放在每个选项单元格中,如下所示:
<option <?php if($value['city'] == "washington") echo "selected=selected"; ?> >washington</option>
这样你就可以得到你想要的。更好地使用mysqli函数进行数据库交互。
<option
<?php if ($value['city'] == delhi)
{
echo "selected = true";
} ?>
>delhi
</option>
只需将所选值从类似的数据库中提取即可
$choosen = $some value form db
那么$options=数组(1=>'data1',2=>'data2',3=>'data3');foreach($options为$key=>$value){echo"$值。'';}
以获取php中的选择框。我想你知道,它对我有效