1

我的桌子是

Section SectionID   SectionHeader
S1      1           Section1
S2      1           Section1
S3      1           Section1
S4      2           Section2
S5      2           Section2
S6      3           Section3
S7      3           Section3

我正在使用以下代码从数据库中获取记录。

<?php  $sql="SELECT * FROM myTable ORDER BY SectionID";
$result=mysql_query($sql); ?>
<select><option value="" selected="selected">Select a Section</option>
<?php   while ($row = mysql_fetch_array($result)) {?>
    <option value="<?php echo $row['SectionID'];?>" > <?php echo $row['Section'];?></option> <?php } ?> </select>

我想在选择菜单中显示每个部分及其部分标题。

所以我的最终输出看起来像:

在此处输入图像描述

请帮忙

4

1 回答 1

0

试试下面的代码

<?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>
于 2013-08-05T04:02:36.270 回答