2

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>

enter image description here

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
IlludiumPu36
  • 4,196
  • 10
  • 61
  • 100
  • 1
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://stackoverflow.com/a/14110189/1723893). – NullPoiиteя Feb 05 '13 at 05:23
  • You can use group by link_title. maybe it will help you. – Devang Rathod Feb 05 '13 at 05:44

1 Answers1

1

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).

TddOrBust
  • 450
  • 2
  • 9