How do I save a select option list from foreach loop

I have a foreach loop which shows a option list with all the countries in it

foreach($countries as $cc => $name) {

echo '<option value="' . $name . '">' . $name . '</option>';
}

The selected option gets saved in the database. What i want to do is that if I go back to this page that it showed the already selected option from the database. How would I do this?

Read More

Thanks.

Related posts

4 comments

  1. just put the selected attribute on the one which you want to select

    foreach ($countries as $name) {
       if ($yourselectedValue == $name) {
           $selected = 'selected';
       } else {
           $selected = '';
       }
       echo '<option value="' . $name . '" '.$selected.'>' . $name . '</option>';
    }
    
  2. Try this:

    //$saved_option = get saved option or selected option
    
    foreach($countries as $cc => $name) {
        if ($saved_option == $name) {
            echo '<option value="' . $name . '" selected="selected">' . $name . '</option>';
        } else {
            echo '<option value="' . $name . '">' . $name . '</option>';
        }
    }
    
  3. Retrieve the country id and store it in a variable

    $query  = "SELECT country_id FROM Tablename WHERE YOUR_CONDITION";
    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) > 0)
    {
    $row    = mysqli_fetch_assoc($result);
    $selectedOption = $row['country_id'];
    }
    else
    {
    $selectedOption = ''; // Your default selection of $cc
    }
    

    Select box

    The below code displays all the options of country array. $cc will check with the database value ($selectedOption) and that country will get selected by default.

    $Option = '';
    foreach ($countries as $cc => $name)
    {
        if ($cc == $selectedOption)
        {
            $Option .= '<option value="'.$cc.'" selected="selected">'.trim($name).'</option>';
        }
        else
        {
            $Option .= '<option value="'.$cc.'">'.trim($name).'</option>';
        }
    }
    
    
    <select name="country_id" id="country_id">
    <?php echo $Option;?>
    </select
    
  4. $previousselect = database query;
    
    foreach($countries as $cc => $name) {
    
    echo '<option value="' . $name .'" '. ($previousselected == $name) ? 'selected' .'>' . $name . '</option>';
    }
    

    Or when you create your select object

    <select name="arbitraryname" value="' . echo($previousselect); . '">
    

    Sorry was just quickly typing it in wasnt going for syntax just the method

    $previousselect = database query;
    
    foreach($countries as $cc => $name) {
    
    echo '<option value="' . $name .'" '. ($previousselect == $name ? 'selected' : '') .'>' . $name . '</option>';
    }
    

    should be the proper syntax

Comments are closed.