PHP选择父和子

时间:2018-01-17 18:38:40

标签: php select option

当我查看包含父类别和子类别的下拉选择菜单时,它显示错误地显示了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>

1 个答案:

答案 0 :(得分:0)

嵌套你的循环可以解决这个问题,但它很麻烦并且很难维护。您有没有使用Join的原因?如果每个类别都有一个sub,为什么不共享索引ID并使用join?它会使格式化更容易。

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