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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

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?
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>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.