Search code examples
phpmysqlselectloopsoptgroup

How to add optgroup to dropdown loop?


I have a loop that displays a list of variables in a dropdown box (based on the filtered category). I'd like to add in option groups (using subcategories) from my table. How can I add this to part of my loop?

In the example below, the category is "countries" and subcategory is "continents". I'd like the countries to be listed within the appropriate continent optgroup.

<select id="country">
  <option value="">Select</option>

 <?php
     $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                              FROM constants WHERE category='Countries'
                              ORDER BY display");
     while ($row = $c_sth->fetch ()) {
       echo '<option value="'.$row['value'].'">'.$row['display'].</option>'."\n";
     }
 ?>

</select>

Solution

  • <?php
     $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                              FROM constants WHERE category='Countries'
                              ORDER BY subcategory, display"); # group by category first
     $current_subcategory = "";
     while ($row = $c_sth->fetch ()) {
       if ($row["subcategory"] != $current_subcategory) { # if category has changed
           if ($current_subcategory != "") { # if there was already a category active
               echo "</optgroup>"; # close it
           }
           echo '<optgroup label="'.$row['subcategory'].'">'; # open a new group
           $current_subcategory = $row['subcategory'];
       }
       echo '<option value="'.$row['value'].'">'.$row['display'].</option>'."\n';
     }
     echo "</optgroup>"; # close the final group
    ?>