PHP Select 父子

PHP Select with Both Parent and Sub

当我查看包含父类别和子类别的下拉 select 菜单时,它无法正确显示 optgroup 标签内的所有父类别,如下所示:

**Cat1 Cat2 Cat3** 
 - Sub
 - Sub 
 - Sub

我的意图是这样的:

**Cat**
 - Sub
**Cat**
 - Sub

等等....

我需要做些什么才能正确显示。

这是当前代码:

<select name="DeleteSubCategory" class="form-control" data-style="btn-new">
 <optgroup label="
  <?php
  require('functions/connect.php');
         $stmt = $connect->prepare("SELECT CategoryID, CategoryName FROM category ORDER BY CategoryName ASC");
  $stmt->execute();
  $stmt->bind_result($CategoryID, $CategoryName);
  while ($stmt->fetch()){
  echo "$CategoryName";
  }
  $stmt->close();
  ?>">
  
  <?php
  require('functions/connect.php');
  $stmt = $connect->prepare("SELECT SubCategoryID, SubCategoryParentID, SubCategoryName FROM subcategory");
  $stmt->execute();
  $stmt->bind_result($SubCategoryID, $SubCategoryParentID, $SubCategoryName);
  while ($stmt->fetch()){
  echo "<option value='$SubCategoryID'>$SubCategoryName</option>";
  }
  $stmt->close();
  ?>
 </optgroup>     
</select>

在收到以下反馈后,我加入了按要求显示的查询:)

<?php
  require('functions/connect.php');
  $stmt = $connect->prepare("SELECT 
  category.CategoryID,
  category.CategoryName,
  subcategory.SubCategoryID, 
  subcategory.SubCategoryParentID,
  subcategory.SubCategoryName
  FROM category
  INNER JOIN subcategory ON category.CategoryID = subcategory.SubCategoryParentID");
  $stmt->execute();
  $stmt->bind_result($CategoryID, $CategoryName, $SubCategoryID, $SubCategoryParentID, $SubCategoryName);
  ?>
  <select name="DeleteSubCategory" class="form-control" data-style="btn-new">
 <?php
  while ($stmt->fetch()){
  ?>
 
 <optgroup label="<?php echo $CategoryName; ?>">
       <option value= "<?php echo $SubCategoryID; ?>"><?php echo $SubCategoryName; ?></option>
 </optgroup> 
  <?php
  }
  $stmt->close();
  ?> 
      </select>

嵌套你的循环可以解决问题,但它很混乱并且维护起来很头疼。您有没有使用 Join 的原因?如果每个类别都可以有一个子类别,为什么不共享一个索引 ID 并使用连接呢?这将使格式化更容易。

https://dev.mysql.com/doc/refman/5.7/en/join.html