无法从导航菜单栏的数据库中获取数据

时间:2017-12-29 05:06:30

标签: php mysql pdo

我正在使用MySQL的PHP​​ PDO创建一个简单的动态菜单。我无法从数据库中获取数据。它显示

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帮助

2 个答案:

答案 0 :(得分:1)

您没有获得$parent_id的价值。

根据您的代码,您需要从外部循环中获取它。

所以,替换

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

通过

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

其中$menu1是循环变量数组。

答案 1 :(得分: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

这个类所做的就是获取原始数据并对其进行编译以便在视图中使用。

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;
    }
}

<强>的index.php

在视图中,您需要获取控制器并获取菜单项。在所有顶级页面的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>