试试下面的代码
<?php
$sql="SELECT * FROM myTable ORDER BY SectionID";
$result=mysql_query($sql);
?>
<select>
<option value="" selected="selected">Select a Section</option>
<?php
$section_id = 0; // this will be initialize here as zero.
while ($row = mysql_fetch_array($result)) {
if ($section_id != $row['SectionID']) {
?>
<option value >----<?php echo $row['SectionHeader'];?>----</option>
<?php
$section_id = $row['SectionID']; // set the value of $section_id as equal to $row['SectionID']
}
?>
<option value="<?php echo $row['SectionID'];?>" > <?php echo $row['Section'];?></option>
<?php } ?>
</select>
编辑
并且对于不可选择的SectionHeader
<?php
$sql="SELECT * FROM myTable ORDER BY SectionID";
$result=mysql_query($sql);
?>
<select>
<option value="" selected="selected">Select a Section</option>
<?php
$section_id = 0; // this will be initialize here as zero.
while ($row = mysql_fetch_array($result)) {
if ($section_id != $row['SectionID']) {
if ($section_id != 0) {
echo "</optgroup>"; // this code will not run for the first time, but from the next it will first close the last opened <optgroup> and than create a new <optgroup>
}
?>
<optgroup label="----<?php echo $row['SectionHeader'];?>---- ">
<!-- the issue was here in the above code. optgroup have label to show as option header -->
<?php
$section_id = $row['SectionID']; // set the value of $section_id as equal to $row['SectionID']
}
?>
<option value="<?php echo $row['SectionID'];?>" > <?php echo $row['Section'];?></option>
<?php } ?>
</optgroup> <!-- This will to close the last opened <optgroup> -->
</select>