1
這裏是我的數據庫:我遇到了麻煩類別和子類別
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
但是這個$我像1, 2, 3, 4
一樣,但是我希望這個值是父類別的值,例如1, 4
,以便我可以在下一個for循環中使用$_POST['cateogoriesMain']
來收集值,在那裏我正在顯示cateogriesSub
,在那裏它將獲得先前爲parent_id = to whatever was selected in the selectbox
的那些數據庫行。我希望這是有道理的。
非常感謝! :) – Jonathan 2010-11-10 19:45:25