我有 3 个表,top_category、bottom_category、products,目前我已经列出了 top_category,我对如何列出第二个类别感到困惑,但是它列出了它,所以它也知道它属于什么 top_category,这就是为什么我有外键父级,所以如果 top_category 例如是:
prod1
prod2
prod3
etc
现在我想将我的底部类别加载到这些 top_categories 中,如下所示:
prod1
-subprod1
-subprod2
-subprod3
prod2
-subprod4
-subprod5
prod3
-subprod6
etc
这是我的数据库:
CREATE TABLE top_category (
id INT PRIMARY KEY,
NAME VARCHAR(100)
);
CREATE TABLE bottom_category (
id INT PRIMARY KEY,
NAME VARCHAR(100) ,
top_category_id INT REFERENCES top_category
);
create table product (
id int primary key,
name varchar(100) ,
bottom_category_id int references bottom_category
);
这是我的 php & html 代码:
<?php
include('dbconnect.php');
try
{
$result = $pdo->query(" SELECT * FROM top_category ORDER BY top_name ASC; ");
} // end try
catch (PDOException $e)
{
echo 'There was a error fetching the products.' . $e->getMessage();
exit();
} // end catch
$products = array();
foreach ($result as $row)
{
$products[] = array('id' => $row['id'],
'top_name' => $row['top_name']);
}
?>
<div class="sidebar">
<h4 class="sidebar-header">Select Products</h4>
<form class="nav-search-form">
<input type="search" name="search" placeholder="Search products">
</form>
<nav class="sidebar-links">
<ul>
<li><a id="red" href="index.php">New Products</a></li>
<?php foreach ($products as $product): ?>
<li><a href="#"><?php echo htmlspecialchars($product['top_name']);?></a>
<?php endforeach; ?>
<ul>
<li><a href="#"></a></li>
</ul>
</li>
</ul>
</nav>
</div><!-- sidebar -->
<div class="main-content">