简体   繁体   中英

Dynamic select list with optgroup from database

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:

<?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 "</optgroup>"; 
       }
       echo '<optgroup label="'.$row['link_category_name'].'">'; 
       $current_subcategory = $row['subcategory'];
   }
   echo '<option value="'.$row['link'].'">'.$row['link_title'].'</option>'."\n";
 }
 echo "</optgroup>"; 
?>
          </select>

在此处输入图片说明

In this line:

$current_subcategory = $row['subcategory'];

Shouldn't "subcategory" be "link_category_name"? Granted, without seeing your database schema, I can't begin to answer that question with any certainty, but the problem appears to be that the record column subcategory's value does not match that of link_category_name (hence why your if condition is always true).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM