【发布时间】:2014-10-03 20:42:06
【问题描述】:
我有两张桌子:
1.文章: id, title, content, catid
2。类别:id, title, parent
现在我想在一个框中显示所有类别。框应包含所有子类别(=parent)作为框和所有文章(=catid)
例如
Box Vegetables (Level 1)
Box Red vegetables (Level 2)
Tomatoes
Beetroot
Box Green vegetables (Level 2)
Cucumber
Other vegetable 1 (article)
Other vegetable 2 (article)
Box Cars (Level 1)
BoxRacing Cars (Level 2)
F1 Racing Car
Nascar Car
Ford Fiesta (article)
Opel Corsa (article)
这是我的 SQL 和 PHP 尝试。
$categories = $db->prepare('SELECT id, title FROM categories');
$subcategories = $db->prepare('SELECT id, title FROM categories WHERE parent = :id');
$articles = $db->prepare('SELECT id, title, content FROM articles WHERE catid = :id');
$categories->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$categories->execute();
if ($categories->rowCount()) {
while($cat = $categories->fetch(PDO::FETCH_OBJ)) {
echo '<div class="list">';
echo cat->title;
$subcategories->bindParam(':id', $cat->id, PDO::PARAM_INT);
$subcategories->execute();
if ($subcategories->rowCount()) {
while($subcat = $subcategories->fetch(PDO::FETCH_OBJ)) {
echo '<div class="list">';
echo subcat->title;
$art->bindParam(':id', $subcat->id, PDO::PARAM_INT);
$art->execute();
if ($art->rowCount()) {
while($article = $art->fetch(PDO::FETCH_OBJ)) {
echo $article->title;
}
}
echo '</div>';
}
}
$art->bindParam(':id', $cat->id, PDO::PARAM_INT);
$art->execute();
if ($art->rowCount()) {
while($article = $art->fetch(PDO::FETCH_OBJ)) {
echo $article->title;
}
}
echo '</div>';
}
}
我可以这样做更有效率吗?我真的需要那么多 SQL 语句和 while 循环吗?
【问题讨论】: