2010-11-10 78 views
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的那些数据库行。我希望这是有道理的。

回答

1

您应该使用数组期权价值的关键,就像这样:

<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']; 
+0

非常感谢! :) – Jonathan 2010-11-10 19:45:25