2017-12-29 6 views
0

MySQL에서 PHP PDO로 간단한 동적 메뉴를 만들고 있습니다. 데이터베이스에서 데이터를 가져 오지 못했습니다. 그것은데이터베이스에서 nav 메뉴 막대의 데이터를 가져올 수 없습니다.

enter image description here

<?php require_once 'include/dbpdo.php'; ?> 
<html> 
    <head> 
     <style> 
     </style> 
    </head> 
    <body> 
     <?php 
     $stmt = $pdo->query('SELECT * FROM `category` where `parent_id` = 0'); 
     $stmt->execute(); 
     ?> 
     <ul> 
      <?php while($menu1 = $stmt->fetch()){ ?> 
       <li><a href="<?php echo $menu1['category_link'] . "\n"; ?>"><?php echo $menu1['product'] . "\n"; ?></a> 

        <?php 
         $stmt1 = $pdo->prepare('SELECT * FROM category WHERE parent_id = ?'); 
         $stmt1->execute([$parent_id]); 
         $stmt1->fetch(); 
        ?> 
        <ul> 
         <?php while($menu2 = $stmt1->fetch()){ ?> 
          <li><a href="<?php echo $menu2['category_link'] . "\n"; ?>"><?php echo $menu2['product'] . "\n"; ?></a></li> 
         <?php } ?> 
        </ul> 
       </li> 
      <?php } ?> 
     </ul> 
    </body> 
</html> 

내 데이터베이스는 다음과 같이 보여줍니다 :

enter image description here

가 Plz은

+3

오류가 명확하게 라인에없는 변수'$의 parent_id'을 보여주는'$ stmt1-> 실행 ([$의 PARENT_ID]);' –

답변

0

실제로 수행해야 할 작업은 모델/컨트롤러 /보기 버전을 만드는 것입니다. 조금 더 복잡해 보이지만,보기에 관해서는 훨씬 더 읽기 쉽습니다.을이 같은 뭔가 (주,이 테스트를하지 않은,하지만 당신은 일이되어 무엇의 아이디어를 얻을 수 있도록 내가 표기 한) :

/config.php

# Create some helpful defines 
define('DS',DIRECTORY_SEPARATOR); 
define('ROOT_DIR',__DIR__); 
define('VENDOR',ROOT_DIR.DS.'vendor'); 
define('INCLUDES',ROOT_DIR.DS.'include'); 
# Create a class autoloader 
spl_autoload_register(function($class){ 
    # You want to turn the class name into a path name so you can easily load 
    # your classes 
    # So this "\MyApp\Page\Model" turns into "/var/html/domain/vendor/MyApp/Page/Model.php" 
    $classPath = str_replace('\\',DS,$class); 
    $path = str_replace(DS.DS,DS,VENDOR.DS.$classPath.'.php'); 
    # If this file exists, include it 
    if(is_file($path)) 
     include_once($path); 
}); 
# Start session (even if you are not using it, look to the future...) 
session_start(); 
# Create database 
require_once(INCLUDES.DS.'dbpdo.php'); 

/vendor/MyApp/Page/Model.php

이 클래스는 데이터를 가져 와서 행을 다시 보냅니다.

namespace MyApp\Page; 

class Model 
{ 
    protected $pdo; 
    /** 
    * @explanation You want to have the connection thrown into the 
    *     construct so this class can use it 
    */ 
    public function __construct(\PDO $pdo) 
    { 
     $this->pdo = $pdo; 
    } 
    /** 
    * @description Creates a way to just extract base categories 
    */ 
    public function getBaseCategories() 
    { 
     $query = $this->pdo->query('SELECT * FROM `category` where `parent_id` = 0'); 
     $rows = []; 
     while($result = $query->fetch(\PDO::FETCH_ASSOC)) { 
      $rows[] = $result; 
     } 

     return $rows; 
    } 
    /** 
    * @description Creates a way to just categories based on a parent 
    */ 
    public function getCategoryByParent($id) 
    { 
     $rows = []; 
     $query = $this->pdo->prepare("SELECT * FROM `category` where `parent_id` = ?"); 
     $query->execute([$id]); 
     while($result = $query->fetch(\PDO::FETCH_ASSOC)) { 
      $rows[] = $result; 
     } 
     return $rows; 
    } 
} 

/vendor/MyApp/Page/Controller.php

이 모든 클래스는 원시 데이터를 가져 와서보기에 사용하기 위해 컴파일입니다 않습니다. 뷰에서 /index.php

namespace MyApp\Page; 

class Controller extends \MyApp\Page\Model 
{ 
    /** 
    * @description Fetches both the parent and child from the model 
    */ 
    public function getMenus() 
    { 
     $menus = []; 
     # Since this class extends the model, it can use it's methods 
     # Get the parent categories 
     $cat = $this->getBaseCategories(); 
     # Loop through those 
     foreach($cat as $row) { 
      # Standardize the return 
      $menus[$row['id']] = [ 
       'id' => $row['id'], 
       'link' => $row['category_link'], 
       'title' => $row['product'] 
      ]; 
      # Fetch the children based on the id of this parent 
      $subs = $this->getCategoryByParent($row['id']); 
      # Skip if none 
      if(empty($subs)) 
       continue; 
      # If there are children, get them assign them 
      foreach($subs as $child) { 
       $menus[$row['id']]['children'][$child['id']] = [ 
        'id' => $child['id'], 
        'link' => $child['category_link'], 
        'title' => $child['product'] 
       ]; 
      } 
     } 

     return $menus; 
    } 
} 

, 여기 당신이 컨트롤러를 얻을 메뉴 아이템을 취득하려고합니다. 모든 최상위 페이지의 config.php에 모든 도우미를 포함 시키십시오.

<?php 
# Include our helper defines and such 
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php'); 
# Create the menu object 
$View = new \MyApp\Page\Controller($pdo); 
?> 
<html> 
    <head> 
     <style> 
     </style> 
    </head> 
    <body> 
     <?php 
     # Get all my menus 
     $MenuItems = $View->getMenus(); 
     # Check there are menus to iterate through 
     if(!empty($MenuItems)): ?> 

     <ul> 
      <?php foreach($MenuItems as $base): #Loop base categories ?> 
       <li> 
        <a href="<?php echo $base['link'] ?>"><?php echo $base['title'] ?></a> 

        <?php 
        # Iterate through any children 
        if(!empty($base['children'])): 
        ?> 
        <ul> 
         <?php foreach($base['children'] as $sub): ?> 
          <li> 
           <a href="<?php echo $sub['link'] ?>"><?php echo $sub['title'] ?></a> 
          </li> 
         <?php endforeach; ?> 
        </ul> 
        <?php endif ?> 
       </li> 
      <?php endforeach; ?> 
     </ul> 

     <?php endif; ?> 
    </body> 
</html> 
1

당신은 $parent_id의 가치를 점점되지 않습니다 도움이됩니다.

코드에 따라 외부 루프에서 가져와야합니다.

그래서 $menu1 루프 변수 배열이다

$stmt1->execute([$menu1['parent_id']]); 

으로

$stmt1->execute([$parent_id]); 

대체.

+0

당신에게 선생님 감사합니다. 가치는 지금 온다. 하지만 이제 전체 트리보기가 표시되지 않습니다. Plz 도움말 –

관련 문제