Вы можете сделать это в одном запросе, используя многомерные массивы:
<?php
$opts = array();
# select all active categories
$qr = mysql_query('SELECT cat_id, cat_group, cat_name FROM categories WHERE cat_status = 1 ORDER BY cat_id ASC');
# go through all results
while ($qa = mysql_fetch_assoc($qr)) {
$opts[$qa['cat_group']][$qa['cat_id']] = $qa['cat_name'];
# e.g. $opts['Vehicles'][1] = 'Cars'
}
/*
# now your array looks like:
$opts = array(
'Vehicles' => array(
1 => 'Cars',
2 => 'Motorcycles',
),
'Properties' => array(
3 => 'Houses',
4 => 'Apartments',
),
'Electronics' => array(
5 => 'Cameras',
6 => 'Gadgets',
)
);
*/
?>
<!-- now output it -->
<select id="category" name="category">
<?php foreach (array('Vehicles', 'Properties', 'Electronics') as $label): ?>
<optgroup label="<?php echo $label ?>">
<?php foreach ($opts[$label] as $id => $name): ?>
<option value="<?php echo $id ?>"><?php echo htmlspecialchars($name); ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>