使用php从select元素中选择选项

时间:2014-08-03 16:50:04

标签: php html mysql

我有一个数据库字段country我想查询并从select元素中选择该国家/地区选项。有没有办法这样做而不添加:

if (query->country == "<some country>"){echo "selected"} 

在每个选项标签中?因为有数百个国家选择。这是代码的一个小例子。谢谢。

$query = $query->fetch_object();

// which ever country is held in the variable `$query->country` should be selected

echo"<select>
       <option>Afghanistan</option>
       ......
       ......
       <option>Zimbabwe</option>
     </select>"; 

2 个答案:

答案 0 :(得分:1)

IF仍然需要被放置&#34;每个<option>,但作为程序员,你应该做这样的事情:

$options = array( 'Afghanistan', '...', 'Zimbabwe' );

foreach( $options as $option )
{
    $selected = ( $query->country == $option )? ' selected': '';
    echo '<option' . $selected . '>' . $option . '</option>';
}

如果您不熟悉三元运算符,则上面的$selected = ...部分可以这样写:

if ( $query->country == $option )
{
    $selected = ' selected';
}
else
{
    $selected = '';
}

答案 1 :(得分:1)

您的服务器上没有所有国家/地区的列表吗?

$countries = ["Afghanistan", ... , "Zimbabwe"];

你可以这样做:

$selection = "Some country";

echo "<select>";

foreach($countries as $country)
{
    if($country == $selection)
        echo "<option selected>" . $country . "</option>";
    else
        echo "<option>" . $country . "</option>";
}

echo "</select>";