【问题标题】:PHP Select with Both Parent and SubPHP 选择同时包含父项和子项
【发布时间】:2018-06-26 17:36:10
【问题描述】:

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

【问题讨论】:

标签: php select option


【解决方案1】:

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

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

【讨论】:

  • 非常感谢罗伯特 :) 我接受了您的建议,我将在我的更新中显示。为此干杯
猜你喜欢
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2018-04-11
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多