接下来我想要建立的是什么。获取我的所有菜单类别并显示它们,然后获取每个类别的所有子类别特别显示它。我希望你明白我的想法和说法。我迷失在代码中,现在不知道如何做到这一点。这是我的代码,希望你能帮助我。
这是表结构。
子类别表
| id | subcategory_name | id_category |
类别表
| id |类别|
id_category与类别表
中的id相关联<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-left">
<?php
$pdo = connect();
$sql = "SELECT * FROM category";
$query = $pdo->prepare($sql);
$query->execute();
$row = $query->fetchAll();
foreach ($row as $rs) { ?>
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo $rs['category'] ?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
$sql = "SELECT subcategory.subcategory_name, subcategory.id_category, category.id, category.category
FROM subcategory
INNER JOIN category
WHERE subcategory.id_category = category.category";
$query = $pdo->prepare($sql);
$query->execute();
$subcat = $query->fetchAll();
foreach ($subcat as $sub) { ?>
<li><a href="#"><?php echo $sub['subcategory_name'] ?></a></li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="includes/logout.php">Logout</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
答案 0 :(得分:3)
我认为你只是不理解INNER JOIN sql select语句。您必须声明第二个表与第一个表的关系:
SELECT column_list
FROM t1
INNER JOIN t2 ON join_condition1
WHERE where_conditions;
在您要将“subcategory.id_category = category.category”部分放入查询的位置加入条件。也许省略实际的WHERE子句? 希望能帮助到你。 看here
编辑: 我建议指出重写完整的代码在一个查询中执行它。但是你的代码可以使用已捕获的变量和第一个sql查询快速简化:
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-left">
<?php
$pdo = connect();
$sql = "SELECT * FROM category";
$query = $pdo->prepare($sql);
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($row as $rs) { ?>
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo $rs['category'] ?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
$sql = "SELECT subcategory_name, id_category
FROM subcategory
WHERE id_category = '".$rs['id']."'";
$query = $pdo->prepare($sql);
$query->execute();
$subcat = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($subcat as $sub) { ?>
<li><a href="#"><?php echo $sub['subcategory_name'] ?></a></li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="includes/logout.php">Logout</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>