Update drop down from SQL database using PHP

803 Views Asked by At

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

There are 3 best solutions below

1
On BEST ANSWER

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

1
On

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

0
On

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