我想知道如何使用下面的代码从用户的配置文件中选择显示正确的状态。现在它默认为空行。
<select id="state" name="state" class="input-xlarge form-control">
<option value=""></option>
<?php
$result = $db->select("SELECT * FROM as_states ORDER BY statename ASC");
foreach($result as $country)
{
echo "<option value=\"";
echo $country['stateid'];
echo "\">";
echo $country['statename'];
echo "</option>";
}
?>
</select>
过去有人告诉我如何以这种方式(下图)这样做,这是较旧的PHP版本,并想知道如何使其在上述声明中工作。
<?php
$sql="SELECT * FROM countries ORDER BY countrypicks DESC,countryname ASC";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result))
{
$countryid=$row["countryid"];
$countryname=$row["countryname"];
$selected = ($countryid == $merchcountry) ? 'selected="selected"' : '';
$options.="<option value=\"$countryid\" $selected>$countryname</option>";
}
?>
<SELECT NAME="merchcountry">
<option>-------</option>
<? echo $options; ?>
</SELECT>
谢谢。
答案 0 :(得分:0)
html应该看起来像
<option value="id" selected>name</option>
(如果您需要兼容xhtml,则选择=“已选择”)
如下所示:
echo "<option value=\"";
echo $country['stateid'];
if ( $country['stateid'] == $user_state ) echo " selected";
echo "\">";
echo $country['statename'];
echo "</option>";
也:
SELECT * FROM countries ORDER BY countrypicks DESC,countryname ASC
如果你只需要stateid和statename,那么就太过分了。