0

I know this should be simple but I just can't seem to get my head around it.

I have a list of continents in a sql database that I get back using PHP DBO and display in a drop down list. What I then want to do is get the users preferred continent from the sql database and select that one in the list. E.g if the list contains World, Africa, Europe, N America and S America but the users favorite is 'Europe' I want that one selected. $getContinent is the users preference.

while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {

    if ($getContinent != ''){
        echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
    }else{
        echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
    }
}

I would be most grateful if someone could set me straight as I have found some examples on the internet but have been unable to get them to work :)

peterm
  • 91,357
  • 15
  • 148
  • 157
James
  • 474
  • 4
  • 9
  • 22

3 Answers3

2

Your code should be like this

while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {

//just check if the option id is equal to the chosen value

    if ($getContinent != '' && $getContinent==$row['CONTINENT_ID'] ){


        echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';

    }else{
        echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
    }
}

Its simple, as you guessed :D

luckystars
  • 1,704
  • 12
  • 12
  • Dam I was close! Thanks for your help that's what I wanted! I could not find any examples using DBO. Will mark you correct in 60 seconds lol :) – James Jan 27 '13 at 20:13
0

You would use something like this:

while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
    echo '<option value="' . $row['CONTINENT_ID'] . '">' . $row['CONTINENT_NAME'] . '</option>';
}

I hope that helps!

--al

Alberto Ponte
  • 479
  • 3
  • 7
  • Thanks for the help, but that would only give me a list from the db which I know how to do. How would I then update the displayed list to show the users choice? – James Jan 27 '13 at 20:07
0

You can use ternary operator

while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
    echo '<option value="' . $row['CONTINENT_ID'] . 
         ($getContinent == $row['CONTINENT_NAME']) ? '" selected="selected"' : '"' . '>' . 
         $row['CONTINENT_NAME'] . '</option>';
}
peterm
  • 91,357
  • 15
  • 148
  • 157