[英]I'm having trouble getting categories and subcategories
這是我的數據庫:
id name parent_id
1 Computers NULL
2 Apple 1
3 Books 1
4 Music NULL
5 CDs 4
6 Records 4
我的類別功能:
public function showCategories($parent_id = 0){
if($parent_id == 0){
$sql = "SELECT * FROM categories WHERE parent_id IS NULL";
} else {
$sql = "SELECT * FROM categories WHERE parent_id =:parentid";
}
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':parentid', $parent_id);
$stmt->execute();
$categories = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
array_push($categories, array($row['id'] => $row['name']));
}
return $categories;
}
這是我的類別頁面:
<?php
//Instantiate categories class
$categories = new categories($db);
$categoriesMain = $categories->showCategories(0);
?>
<html>
<head></head>
<body>
<form action="" method="post">
<?php //Get parent categories and put them into a select box ?>
<select name="categoriesMain">
<?php for($i=0;$i<count($categoriesMain);$i++){ ?>
<option value="<?php echo $i; ?>">
<?php echo $categoriesMain[$i]; ?>
</option>
<?php } ?>
</select>
<input type="submit" name="submit" value="submit"/>
</form>
<?php //if form submits then show sub categories ?>
<?php if(isset($_POST['submit'])){
$categoriesSub = $categories->showCategories($_POST['categoriesMain']);
for($i=0;$i<count($categoriesSub);$i++){
echo $categoriesSub[$i];
}
} ?>
</body>
</html>
讓我嘗試解釋我遇到的麻煩。 我認為我的整個設計不合時宜,因為感覺就像那樣,但我目前腦子里有障礙。
在函數中,我返回一個數組,例如Array ( [0] => Array ( [1] => Computers ) [1] => Array ( [4] => Music ) )
。 如果您認為這是錯誤的退貨方式,請告訴我。 好的,那么您看到CategoriesMain
嗎? 我正在使用for循環來輸出此數組,並且使用option=value im echoing $i
但是此$ i類似於1, 2, 3, 4
但是我希望該值是父類別的值,例如1, 4
這樣我就可以在下一個for循環中使用$_POST['cateogoriesMain']
來收集值,在該循環中我將顯示cateogriesSub
,它將在其中獲取具有parent_id = to whatever was selected in the selectbox
先前parent_id = to whatever was selected in the selectbox
的數據庫行。 我希望這是有道理的。
您應該使用數組的鍵作為選項值,如下所示:
<select name="categoriesMain">
<?php foreach ($categoriesMain as $k => $v) { ?>
<option value="<?php echo $k; ?>">
<?php echo $v; ?>
</option>
<?php } ?>
</select>
編輯還可以在php函數中更改以下行,而不是:
array_push($categories, array($row['id'] => $row['name']));
做
$categories[$row['id']] = $row['name'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.