Search code examples
phpdrop-down-menudbo

Update drop down from SQL database using PHP


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


Solution

  • 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