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


i want http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup have main categories , subcategories in db, , don't know how manage in while cycle. how can ? cycle that, because of necessities can't use anymore

<select  class="form-control" id="subcategory" name="subcategory" required> <?php    $categories="select name,category subcategory order 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 main category, name subcategory

i want have main category <optgroup> because of 1 category contains more 1 subcategory, don't know how place <optgroup> in way shows main category 1 time , not each record.

in case, need flag if current main category has added on html, if understand fields in database, name , category has string values , don't need 2 queries or 2 whiles check variable, this:

<select  class="form-control" id="subcategory" name="subcategory" required> <?php $categories="select name,category subcategory order category asc, name asc;"; $query_categories=mysqli_query($connh,$categories);  $currentmaincategory = null; while($rows_categories=mysqli_fetch_array($query_categories)){     // check if current category diferent of row category     if($currentmaincategory != $rows_categories['category']) {          // check if not null (for close </optgroup>)          if(!is_null($currentmaincategory)) {               echo '</optgroup>';          }          // set new current category loop          $currentmaincategory = $rows_categories['category'];          echo '<optgroup label="'. $rows_categories['category'] .'">';     }     // not forget put value of category if needed     echo'<option>' . $rows_categories['name'] . '</option>';   }  // check again close last optgroup if opened if(!is_null($currentmaincategory)) {    echo '</optgroup>'; } ?> </select> 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -