我想要做的是創建一個從數據庫中拉出的類別列表,然後列出這些類別下的每個相關子類別 。使用嵌套的while循環沒有給出所需的輸出
到目前爲止我有:
<?php
// this query lets us know that we are looking for matches that equal 2, which points to the subject of vehicles.
// from this query i am able to list all categories that are relevant to vehicles.
$getCategoriesQuery = $db->query("SELECT * FROM item_cat WHERE sub_id = '2'"); //2 = vehicles
?>
<?php
while($row = $getCategoriesQuery->fetch()){
echo '<ul>'.$row['category'].'';
}
?>
其中顯示:
- motor vehicles
- railed vehicles
- aircraft
現在,當我添加下面的while循環上面的一個:
<?php
while($row = $getCategoriesQuery->fetch()){
echo '<ul>'.$row['category'].'';
// this has been added to try and get the sub categories
$getSubCatQuery = $db->query("SELECT * FROM item_cat, item_sub_cat
WHERE item_cat.cat_id = item_sub_cat.cat_id "); // cat_id
while($row = $getSubCatQuery->fetch()){
echo '<li><a href="vehicles.php?p='.$row['sub_category'].'" >'.$row['sub_category'].'</a></li>';
}
echo '</ul>';
}
?>
我得到:
- motor vehicles
- cars
- motorbikes
- buses
- trucks
- trains
- planes
-railed vehicles
- cars
- motorbikes
- buses
- trucks
- trains
- planes
-aircraft
- cars
- motorbikes
- buses
- trucks
- trains
- planes
當什麼,我想要做的是:
-motor vehicles
- cars
- motorbikes
- buses
- trucks
-railed vehicles
- trains
-aircraft
- planes
我曾嘗試加入查詢開始的,但沒有快樂,所以我分成2個查詢來試試,看看事情會好一點。 我已經在第二個while循環中將「$ row」更改爲「$ row2」,但是這樣會給我一個未定義的索引錯誤「row2 ['sub_category']」
我也嘗試使用「foreach循環「而不是第二個‘while循環’:
<?php
// this query lets us know that we are looking for matches that equal 2, which points to vehicles.
$getCategoriesQuery = $db->query("SELECT * FROM item_cat WHERE sub_id = '2'"); //vehicles
?>
<?php
while($row = $getCategoriesQuery->fetch()){
echo '<ul>'.$row['category'].'';
$getSubCatQuery = $db->query("SELECT * FROM item_cat, item_sub_cat
WHERE item_cat.cat_id = item_sub_cat.cat_id "); // cat_id
foreach ($getSubCatQuery->fetchAll() as $row2) {
echo '<li><a href="vehicles.php?p='.$row2['sub_category'].'" >'.$row2['sub_category'].'</a></li>';
}
echo '</ul>';
}
?>
我花了一整天試圖解決這個問題,但沒有喜悅 - 只是頭痛。任何人都可以請告訴我哪裏錯了...我錯過了什麼? - 如果不明確,我也在使用PDO。
在此先感謝!
--UPDATED-- 我已經改變了而循環部分:
<?php
while($row = $getCategoriesQuery->fetch()){
echo '<ul>'.$row['category'].'';
$getSubCatQuery = $db->query("SELECT * FROM item_sub_cat, item_cat WHERE item_sub_cat.cat_id ='".$row['cat_id']."' ");
while($sub_row = $getSubCatQuery->fetch()){
echo '<li><a href="vehicles.php?p='.$sub_row['sub_category'].'" >'.$sub_row['sub_category'].'</a></li>';
}
echo '</ul>';
}
?>
和輸出被顯示在正確的類別的東西....然而它是由總複製的每個項目記錄我在數據庫:
- motor vehicles
- cars
- motorcycles
- trucks
- buses
- cars
- motorcycles
- trucks
- buses
- cars
- motorcycles
- trucks
- buses
- cars
- motorcycles
- trucks
- buses
- cars
- motorcycles
- trucks
- buses
- railed vehicles
- trains
- trains
- trains
- trains
- trains
我已經加入「LIMIT 1」和「GROUP BY」的查詢嘗試過,但後來只顯示每類1項。
- motor vehicles
- cars
- railed vehicles
- trains
你應該使用'GROUP BY'而不是'limit',這應該檢索結果。 –