title: Dynamic select list with optgroup from database
body: <p>I have the following code populating a select list, however each option ('link_title') has a optgroup heading above it in the list, instead of grouping options into optgroup headings:</p>
  
  <pre><code>&lt;?php   
  $query = mysql_query("SELECT * from link, link_category WHERE link.link_category_fk = link_category.link_category_pk ORDER BY link_category_fk, link_title ASC");
  $current_subcategory = "";
  while ($row = mysql_fetch_array($query)){
  
     if ($row["link_category_name"] != $current_subcategory) { 
         if ($current_subcategory != "") { 
             echo "&lt;/optgroup&gt;"; 
         }
         echo '&lt;optgroup label="'.$row['link_category_name'].'"&gt;'; 
         $current_subcategory = $row['subcategory'];
     }
     echo '&lt;option value="'.$row['link'].'"&gt;'.$row['link_title'].'&lt;/option&gt;'."\n";
   }
   echo "&lt;/optgroup&gt;"; 
  ?&gt;
            &lt;/select&gt;
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/6VKPo.jpg" alt="enter image description here"></p>