Daniel West
Daniel West

Reputation: 1808

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

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 simple solution to this problem?

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

Thanks.

Upvotes: 0

Views: 616

Answers (2)

FatherStorm
FatherStorm

Reputation: 7183

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

Upvotes: 1

spamoom
spamoom

Reputation: 464

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 :)

Upvotes: 2

Related Questions