Announcement

Collapse
No announcement yet.

Retrieve select box value from database using PHP

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Retrieve select box value from database using PHP

    Retrieve select box value from database using PHP

    I have been in many situations in designing a html form where i want the value stored in database selected in select box when editing the user data.

    For example if i have colors like Red, Green, Blue, Yellow, Violet shown in selectbox and if the user selected Green and previously stored in database, then we need to show the select box with Green as selected value. This kind of situation arises, while editing or making changes to database content.

    Here is the very simple php code to accomplish that task.

    First we hold all select box colors in an array, then we compare each array element to the value stored in database. If it matches, then we output selected option else we output unselected option. In this way all the selectbox options are shown with selected one.


    Code:
    <select name="color">
    <?php
    //Array of colors for selectbox
    $aColors = array("Red", "Blue", "Green", "Yellow", "Violet");
    $dbcolor = "Yellow"; // stored in database
     
    foreach ($aColors as $color)
    {
    if($color == $dbcolor) {
     echo "<option value=\"$color\" SELECTED>$color</option>";
     } else
     {
      echo "<option value=\"$color\">$color</option>";
      }
    }
     
    ?>
    </select>
Working...
X