using php in select with optgroup

Hello,

Yes, I want my to use php to get the data i have on my database to provide the info for the drop down. I am using the select tag. Here is the scenario, i have a table of locations, which include the city and state(here it is called area). In my drop down i want to use optgroup to separate or group my cities into the different states they are in. So far this is my code:

[code] Find one near you

<?php $query = mysql_query("SELECT city,area FROM `location` group by `area`",$db_conn); while ($result = mysql_fetch_array($query)){ ?> <?php echo $result['city']?> <?php } ?> [/code]

With this code i was able to get the result of one area and one city and it displays the next area and one city again, it doesnt list all the cities under that area,
You have any suggestions ? :-?

One possible way could be :

// Initialize some variables
$area = ""; 
$groupOpen = false; 

while ($result = mysql_fetch_array($query)){

   // Checks for a NEW area and Opens the OPTGROUP if it's a NEW area
   if ($result['area'] != $area) {
      // New Group... Is there an OPEN group?
      if ($groupOpen == true) {
           echo "</optgroup>";  // Close the open group and get ready for a new one.
           $groupOpen = false;
      }
    
      $area = $result['area'] ;
      echo '<optgroup label="'.$area.'">";
      $groupOpen = True;  // set a flag so we know to CLOSE the group if needed
   } else {
      // If we got here... there must be a group open 
      // Echo the OPTIONS for this group
      echo '<option value=".$result['city'].'">'.$result['city'].'</option>';
   }

}
echo '</optgroup>'; //Close the LAST group
?>
Sponsor our Newsletter | Privacy Policy | Terms of Service