尝试创建类别和子类别下拉菜单

时间:2019-02-19 12:04:05

标签: php

我正在尝试使用PHP创建一个类别和子类别下拉菜单,我创建了两个表=称为类别的表,其中包含类别和名称的ID,并且我创建了一个子类别,其中包含了ID的子类别子类别。主要类别的ID和子类别的名称,但是对于所有主要类别,我只得到相同的子类别名称,并且未链接到我设置的实际名称

模型

<?php
class Post{

private $db;
public function __construct(){
  $this->db = new Database;
 }

 public function getcat(){
   $this->db->query('SELECT * FROM categoires');

   $results = $this->db->resultSet();
   return $results;
 }


public function getsubcat(){

$cat = $this->getcat();

$id = $cat[0]->id;


$this->db->query('SELECT * FROM sub_cat WHERE 
cat_id =:cat_id');




 $this->db->bind(':cat_id', $id);
 $results = $this->db->resultSet();
 return $results;

}

}

控制器

     public function index(){





     $cats = $this->postModel->getcat();

     $sub_cats = $this->postModel->getsubcat();



      $data = [

               'cats'=> $cats,
               'sub_cats' => $sub_cats
                 ];

    $this->view('posts/index', $data);
  }

视图

    <?php foreach($data['cats'] as $cats) : ?> 

<li>


 <?php echo $cats->cat_name; ?>


     <?php foreach($data['sub_cats'] as $sub_cats) : ?> 
      <ul>
           <li><?php echo $sub_cats->sub_name; ?></li>
       </ul>
      <?php endforeach; ?>


</li>


<?php endforeach; ?>

数据库类

我已经创建了此类来绑定值并创建准备好的语句

<?php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;

private $dbh;
private $stmt;
private $error;

public function __construct(){
  // Set DSN
   $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    $options = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  );

  // Create PDO instance
  try{
    $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
  } catch(PDOException $e){
    $this->error = $e->getMessage();
    echo $this->error;
  }
}

// Prepare statement with query
public function query($sql){
  $this->stmt = $this->dbh->prepare($sql);
}

// Bind values
public function bind($param, $value, $type = null){
  if(is_null($type)){
    switch(true){
      case is_int($value):
        $type = PDO::PARAM_INT;
        break;
      case is_bool($value):
        $type = PDO::PARAM_BOOL;
        break;
      case is_null($value):
        $type = PDO::PARAM_NULL;
        break;
      default:
        $type = PDO::PARAM_STR;
    }
  }

  $this->stmt->bindValue($param, $value, $type);
}

// Execute the prepared statement
public function execute(){
  return $this->stmt->execute();
}

// Get result set as array of objects
public function resultSet(){
  $this->execute();
  return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}

// Get single record as object
public function single(){
  $this->execute();
  return $this->stmt->fetch(PDO::FETCH_OBJ);
}

// Get row count
public function rowCount(){
  return $this->stmt->rowCount();
}
}

因此,根据我编写的代码,它似乎仅从类别表中获取第一个ID并循环使用相同的名称

categoires Table

sub_cat table

The output i get

3 个答案:

答案 0 :(得分:1)

您的getsubcat()函数有问题。

$cat = $this->getcat();

$id = $cat[0]->id;

$cat_name = $cat[0]->cat_name;

$this->db->query('SELECT * FROM sub_cat WHERE 
cat_id =:cat_id');

$this->db->bind(':cat_name', $cat_name);

$this->db->bind(':cat_id', $id);

您可以使用getcat()选择所有类别,这很好,但是仅选择第一行之后即可:

$id = $cat[0]->id;

$cat_name = $cat[0]->cat_name;

所以这就是为什么无论类别如何都针对此特定查询获得相同结果的原因。而且您所有的子猫都是相同的,并且等于第一类的子猫。

编辑示例:

public function getCategoriesWithSubCategories(){

    $categoriesWithSubCategories = array();

    $categories = $this->getcat();

    foreach ($categories as $category) {
        $this->db->query('SELECT sub_name FROM sub_cat WHERE cat_id =:cat_id');
        $this->db->bind(':cat_id', $category->id);
        $subCategories = $this->db->resultSet();

        $subCategories_labels = array();
        foreach ($subCategories as $subCategory) {
            array_push($subCategories_labels, $subCategory->sub_name);
        } // end of subcategories loop

        $categoriesWithSubCategories[$category->cat_name] = $subCategories_labels;

    } // end of categories loop

    return $categoriesWithSubCategories;

} // end of function

更新您的控制器以仅使用此功能。因此,您将处理单个数组。

然后您的输出将是这样的:

    foreach ($data['array_with_results'] as $cats => $subcats) { 
        echo '<li>' . $cats;

        foreach ($subcats as $subcat) {
            echo '<li><ul>' . $subcat . '</ul></li>';
        }

        echo '</li>';
    }

答案 1 :(得分:0)

public function getsubcat(){

$cat = $this->getcat();

$id = $cat[0]->id;

$cat_name = $cat[0]->cat_name;

$this->db->query('SELECT * FROM sub_cat WHERE cat_name = :cat_name and 
cat_id =:cat_id');


 $this->db->bind(':cat_name', $cat_name);

 $this->db->bind(':cat_id', $id);
 $results = $this->db->resultSet();
 return $results;

} 
$id = $cat[0]->id;

$cat_name = $cat[0]->cat_name;

在这里设置$ cat [0] 所以只有第一个

添加foreach或

$cat = $this->getcat();

for($i=0 ; i<count($cat);$i++){

$id = $cat[$i]->id;

$cat_name = $cat[$i]->cat_name;
$cat = $this->getcat();

// query ... fetch ...
// save as $array[$i]=$results
}
// return $array

答案 2 :(得分:0)

在类别表中创建一个子域,并取字段名称2