开发者

Populate DropDown and Get Selected Value From Database

I have the code to select the values from a 开发者_开发知识库database for populating my drop down list. But my question is if I stored the value of what the user selected in another database, how would I go about pulling that back out and making that the selected choice.

<select name="dropdown1" id="dropdown1">

<?php
for ($i = 0; $i < 5; $i++)
{
    print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
}
?>
</select>

So the users stored value is lets say red. How would I make red the selected value as it populates my drop down list?

Thanks e


<select name="dropdown1" id="dropdown1">

<?php
$selected = "red";

for ($i = 0; $i < 5; $i++)
{
    if ($options[$i]['Value'] == $selected) {
        print '<option selected="selected" id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
    } else {
        print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
    }
}
?>
</select>


On each element test the value. If the value is selected, print 'selected'.

<select name="dropdown1" id="dropdown1">
<?php
$selected = 'red';// obviously replace with DB value.
for ($i = 0; $i < 5; $i++)
{
    // start as normal
    print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'"';

    // if this one is selected, add 'selected' to the tag.
    // NOTE: booleans in HTML do not need to have an attribute value.
    // so selected="selected" is not necessary here.
    if( $options[$i]["Value"] == $selected ) print ' selected';

    // finish as normal
    print '>'.$options[$i]["Name"].'</option>'."\n";
}
?>
</select>

As a side note: if you use foreach it will make for smaller, more compact, and often faster code:

//this assumes that you want to iterate the whole options array
foreach( $options as $option )
{
    print '<option id="'.$option["ID"].'" value="'.$option["Value"].'"';
    if( $option["Value"] == $selected ) print ' selected';
    print '>'.$option["Name"].'</option>'."\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜