Erik Nucibella Erik Nucibella - 5 months ago 20
PHP Question

How to put in a <select> categories and Subcategories from a DB?

i really want to do something like this http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup
but i have The main Categories and the subcategories in a DB, and i don't really know how to manage this in a while cycle. How can i do this ? Actually the cycle is something like that, but because of my necessities i can't use it anymore

<select class="form-control" id="subcategory" name="subcategory" required>
<?php
$categories="SELECT Name,Category FROM SubCategory ORDER BY Category ASC, Name ASC;";
$query_categories=mysqli_query($connh,$categories);

while($rows_categories=mysqli_fetch_array($query_categories)){

echo'<option>'.$rows_categories['Category'].'/'.$rows_categories['Name'].'</option>';
}
?>
</select>


p.s: Category is the main Category, Name is the subcategory

I want to have the main category into
<optgroup>
but because of one Category contains more than 1 subcategory, I don't know how to place
<optgroup>
in a way that it shows the main category just 1 time and not for each record.

Answer

In your case, need flag if current main category has added on your html, if I understand fields in your database, Name and Category has string values and you don't need two queries or two whiles but only check variable, like this:

<select  class="form-control" id="subcategory" name="subcategory" required>
<?php
$categories="SELECT Name,Category FROM SubCategory ORDER BY Category ASC, Name ASC;";
$query_categories=mysqli_query($connh,$categories);

$currentMainCategory = null;
while($rows_categories=mysqli_fetch_array($query_categories)){
    // check if your current category was diferent of row category
    if($currentMainCategory != $rows_categories['Category']) {
         // check if is not null (for close </optgroup>)
         if(!is_null($currentMainCategory)) {
              echo '</optgroup>';
         }
         // set your new current category for this loop
         $currentMainCategory = $rows_categories['Category'];
         echo '<optgroup label="'. $rows_categories['Category'] .'">';
    }
    // do not forget put value of this category if you needed
    echo'<option>' . $rows_categories['Name'] . '</option>';  
}

// then check again for close last optgroup if is opened
if(!is_null($currentMainCategory)) {
   echo '</optgroup>';
}
?>
</select>
Comments