gpt4 book ai didi

php - 使用部分标题将记录提取到选择菜单

转载 作者:行者123 更新时间:2023-11-30 23:15:29 26 4
gpt4 key购买 nike

我的 table 是

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>

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

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

enter image description here

请帮忙

最佳答案

试试下面的代码

<?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>

关于php - 使用部分标题将记录提取到选择菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18050359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com