MySQL加入一个表。使用where子句列出值,然后列出下面的值

时间:2014-04-19 07:23:27

标签: php mysql join

我正在编写一个小脚本以获得一些乐趣并学习更多关于PHP / MySQL的内容,并且我已经走到了生成菜单的死胡同。我的目的是生成一个CSS样式的下拉菜单,您将鼠标悬停在菜单项上,然后在下面显示一个子页面列表。

我脚本中的页面存储在名为“pages”的MySQL表中。这是MySQL的一个例子。

---------------------------------------------------------------------------------
id   title         linkText    menu       pageContent
1    Home          Home        top        This is my home page.
2    Projects      Projects    top        This page is a list of my projects
3    Music         Music       Projects   This page is about my music
4    Photography   Photos      Projects   This page has photography work
5    Art & Craft   Artwork     Projects   This page is all about art and craft work
6    Contact Me    Contact     top        Send me a message

我希望能够对MySQL语句做的是列出'menu'字段等于'top'的项目,这很简单。

SELECT title, linkText, menu FROM pages WHERE menu = 'top'

但我坚持的部分是列出顶部项目,然后在每个顶部项目下方列出子项目,以提供类似的输出。

Home
Projects
--Music
--Photos
--Artwork
Contact

我想这可以通过mysql连接来完成,但在尝试了许多不同的组合并遵循一系列示例之后,我似乎无法使其正常工作。

非常感谢任何帮助。

谢谢

2 个答案:

答案 0 :(得分:0)

如果您想在PHP中获得答案,我可以给您:

try
{
  $bdd = new PDO('mysql:host=localhost;dbname=cours', 'root', 'root');
}
catch(Exception $e)
{
  die('Erreur : '.$e->getMessage());
}

$answer = $bdd->query('SELECT linkText FROM stack WHERE menu = \'top\'');

while ($data = $answer->fetch())
{
  echo $data['linkText'] . "<br/> \n";
  $answer2 = $bdd->prepare('SELECT linkText FROM stack WHERE menu = ?');
  $answer2->execute(array($data['linkText']));
  while ($data2 = $answer2->fetch())
  {
    echo "--" . $data2['linkText'] . "<br/> \n";
  }
  $answer2->closeCursor();
}
$answer->closeCursor();

这给了我HTML的结果:

Home<br/> 
Projects<br/> 
--Music<br/> 
--Photos<br/> 
--Artwork<br/> 
Contact<br/> 

答案 1 :(得分:0)

你可以这样做:

<?php
// SQL for creating database
/*
 CREATE TABLE `menu` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `linkText` varchar(255) NOT NULL,
  `menu` varchar(255) NOT NULL,
  `pageContent` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
*/

class Menu {
    /**
     * @var PDO
     */
    private $_dbh;

    /**
     * Constructor
     *
     * @param PDO $dbh database connection
     */
    public function __construct(PDO $dbh){
        $this->_dbh = $dbh;
    }

    /**
     * Get menu
     *
     * @return array
     */
    public function getMenu(){
        return $this->getTree($this->getTop());
    }

    /**
     * Get top menu
     *
     * @return array
     */
    private function getTop(){
        return $this->_dbh->query("SELECT * FROM menu WHERE menu = 'top'")->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get children menu for specified parent menu
     *
     * @param array $menu
     * @return array
     */
    private function getChildren(array $menu){
        $stmt = $this->_dbh->prepare("SELECT * FROM menu WHERE menu = :menu");
        $stmt->bindParam(':menu', $menu['linkText']);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get menu tree
     *
     * @param array $parents parent menus
     * @param array $tree tree representing menu
     * @return array
     */
    private function getTree(array $parents, array $tree = array()){
        foreach ($parents as $parent){
            $tree[$parent['id']] = $parent;
            $children = $this->getChildren($parent);

            if (!empty($children)){
                $parent['children'] = $children;
                $tree[$parent['id']] = $parent;
                $this->getTree($children, $tree);
            }
        }

        return $tree;
    }
}

$dbh = new PDO('mysql:host=localhost;dbname=stackoverflow', 'root', 'root');
$menu = new Menu($dbh);

echo '<pre>'; print_r($menu->getMenu());

结果是一个树(由数组实现),表示整个菜单结构:

Array
(
    [1] => Array
        (
            [id] => 1
            [title] => Home
            [linkText] => Home
            [menu] => top
            [pageContent] => This is my home page.
        )

    [2] => Array
        (
            [id] => 2
            [title] => Projects
            [linkText] => Projects
            [menu] => top
            [pageContent] => This page is a list of my projects
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [title] => Music
                            [linkText] => Music
                            [menu] => Projects
                            [pageContent] => This page is about my music
                        )

                    [1] => Array
                        (
                            [id] => 4
                            [title] => Photography
                            [linkText] => Photos
                            [menu] => Projects
                            [pageContent] => This page has photography work
                        )

                    [2] => Array
                        (
                            [id] => 5
                            [title] => Art & Craft
                            [linkText] => Artwork
                            [menu] => Projects
                            [pageContent] => This page is all about art and craft work
                        )

                )

        )

    [6] => Array
        (
            [id] => 6
            [title] => Contact Me
            [linkText] => Contact
            [menu] => top
            [pageContent] => Send me a message
        )

)

您也可以在此处找到代码:http://pastebin.com/NcmrJmY3