0

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

user1823053
  • 67
  • 1
  • 2
  • 8

2 Answers2

1

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

Community
  • 1
  • 1
Arthur Yakovlev
  • 8,933
  • 8
  • 32
  • 48
0
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';
}
TMH
  • 6,096
  • 7
  • 51
  • 88
  • Thanks for this the main problem i have is that I am getting selected="selected" in each option where I need just the word selected against one of them - the same as the value from the database. thanks. – user1823053 Jan 08 '14 at 09:28
  • I have fixed this now I wasnt getting a value for $sleeps – user1823053 Jan 08 '14 at 09:43