Following is piece of code that shows HTML select and optgroup tags building using PHP and MySQL. The following example is based of the database structure in OpenCart. Also, it is assumed that the select tags are already part of existing HTML.
$q =' SELECT od.name AS option_sub_type, ovd.option_value_id, ovd.name AS option_value_name FROM oc_option_description od LEFT JOIN oc_option_value_description ovd ON od.option_id = ovd.option_id WHERE ovd.name IS NOT NULL AND od.option_id = ' . $_GET['option_id'] . ' ORDER BY od.name, ovd.name '; $res = mysql_query($q); $str = ''; $outgroup = ''; while($row = mysql_fetch_assoc($res)) { if($outgroup != $row['option_sub_type']) { $str .= '<optgroup label="'.$row['option_sub_type'].'">'; } $str .= '<option value='.$row['option_value_id'].'>'.$row['option_value_name'].'</option>'; if($outgroup != $row['option_sub_type']) { $str .= '</optgroup>'; } $outgroup = $row['option_sub_type']; } echo $str;
And sample result is as follows: