根据数据库变量选择默认选项

问题描述:

我有一个表单,带有一个简单的选择框,并且我也有一个文本字段来提取值。我想使用 $ Defaultselection 中的值作为select选项的默认值。因此,如果 $ Defaultselection = 4,那么默认选择的选项就是D.

I have a form, with a simple select box, and I also have a text field that pulls a value. I want to use the value in $Defaultselection as the default value for the select options. So that if $Defaultselection = 4 then the default selected option would be D.

使用PHP / HTML



Using PHP/HTML

`$Defaultselection` 

包含一个1-4之间的整数。

contains an integer between 1-4.

<select >
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select> 


应该这样做:

<select >
    <option value="1" <?php echo ($Defaultselection == 1)?"selected":""; ?>>A</option>
    <option value="2" <?php echo ($Defaultselection == 2)?"selected":""; ?>>B</option>
    <option value="3" <?php echo ($Defaultselection == 3)?"selected":""; ?>>C</option>
    <option value="4" <?php echo ($Defaultselection == 4)?"selected":""; ?>>D</option>
</select> 

或另一个:

or this other one:

<select >
    <option value="1" <?php if ($Defaultselection == 1) echo "selected"; ?>>A</option>
    <option value="2" <?php if ($Defaultselection == 2) echo "selected"; ?>>B</option>
    <option value="3" <?php if ($Defaultselection == 3) echo "selected"; ?>>C</option>
    <option value="4" <?php if ($Defaultselection == 4) echo "selected"; ?>>D</option>
</select>