开发者

Choosing a value in a drop down box based on database query

开发者 https://www.devze.com 2023-02-16 07:14 出处:网络
I basically need to create a value by default for a drop down menu on a PHP page that will use the value previously selected and stored in the database.

I basically need to create a value by default for a drop down menu on a PHP page that will use the value previously selected and stored in the database.

For example, lets just say I have the value '3' stored in a database column. I want to use this number as the default value for a drop down menu where the <option value = "3">Good</option>. Is there a 开发者_C百科simple solution to this problem?

Or do i literally need to loop through the values until it makes a value?

Thanks.


I usually do this

<?php
    $sel = 'selected="selected"';
    $current_whatever = 5;
?>

<option name="whatever">
    <?php foreach($list as $listItem): ?>
        <option value="<?=$listItem->id?>" <?=($listItem->id == $current_whatever)?$sel:''?>><?=$listItem->name?></option>
    <?php endforeach; ?>
</option>

I'm using an inline if statement to check each one :) Looks reasonably tidy.

Assuming you're using database objects, you get the idea if you're not though :)


<?php foreach($options as $key=>$option){?>
<option value='<?=$key?>' <? echo $key==$selected?"SELECTED":"";?> ><?=$option?></option>
<? }?>
0

精彩评论

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