user1823053
user1823053

Reputation: 69

Get value of a mysql record and show in drop down

I have a mysql entry as an integer 1 to 10. I want to display the result pre selected in a drop down. I am using -

<select name="Sleeps">
<?php
 $sleeps = $row['Sleeps'];

 $selectedId = array(1, 2, 3);
 $selection = array(
        1 => "1",
        2 => "2",
        3 => "3" );

 foreach($selection as $value){
    $text = $value;
    $selected = '';
    if ($selectedID == $sleeps) {
        $selected = 'selected';
    }
    echo '<option value="'.$text.'" selected="'.$selected.'">'.$text.'</option>';
 }
?>
</select>

This nearly works as I get -

<option value="1" selected="selected">1</option>
<option value="2" selected="selected">2</option>
<option value="3" selected="selected">3</option> 

But all options have selected="selected" and i just want the value I have in my db selected which I believe should just be 'selected' text like -

2

Please help I am new to this

Upvotes: 0

Views: 135

Answers (2)

TMH
TMH

Reputation: 6246

if ($selectedID == $sleeps) {
    $selected = 'selected';
}

Should be

if ($text == $sleeps) {
    $selected = 'selected';
}

selectedID isn't defined anywhere, however, selectedId is, and if you want it to be sleected for any number in the array, use

if (in_array($sleeps, $selectedID)) {
    $selected = 'selected';
}

Upvotes: 0

Arthur Yakovlev
Arthur Yakovlev

Reputation: 9309

I think this is types mistake. Try using "===" or if this rows is text convert to int How contert text to int

Upvotes: 1

Related Questions