从mysql数据库创建动态菜单

时间:2017-03-03 09:23:13

标签: php mysqli twitter-bootstrap-3

您正在尝试从我的数据库创建动态菜单。看过很多例子,但我似乎不理解它们。这就是我的数据库的样子

CREATE TABLE IF NOT EXISTS `menu_main` (
`menu_id` int(11) NOT NULL AUTO_INCREMENT,
`menu_name` varchar(50) NOT NULL,
`menu_link` varchar(50) NOT NULL,
`parent_id` varchar(50) NOT NULL,
PRIMARY KEY (`menu_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

这就是我想要实现的目标

<ul class="nav navbar-nav">
          <li class="active"><a href="index.php">Home</a></li>
          <li><a href="#">All Products<span class="caret"></span></a>
            <ul class="dropdown-menu">  
              <li><a href="#">shoes</a></li>              
              <li><a href="#">cloth</a></li>
              <li><a href="#">electronics</a></li>
              <li><a href="#">furniture<span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#">chairs</a></li>
                  <li><a href="#">stand</a></li>
                  <li><a href="#">pocher</a></li>          
                </ul>
              </li>
            </ul>
          </li>
      <li><a href="#">Mission</a></li>

          <li><a href="#">Order</a></li>      

          <li><a href="#">About Us </a></li>
        </ul>

1 个答案:

答案 0 :(得分:1)

这是sql

CREATE TABLE `menu` (
  `id` int(11) NOT NULL auto_increment,
  `label` varchar(50) NOT NULL default '',
  `link` varchar(100) NOT NULL default '#',
  `parent` int(11) NOT NULL default '0',
  `sort` int(11) default NULL,
 PRIMARY KEY  (`id`),
) ENGINE=MyISAM AUTO_INCREMENT=248 DEFAULT CHARSET=latin1;

PHP函数

function display_children($parent, $level) {
    $result = mysql_query("SELECT a.id, a.label, a.link, Deriv1.Count FROM `menu` a  LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent);
    echo "<ul>";
    while ($row = mysql_fetch_assoc($result)) {
        if ($row['Count'] > 0) {
            echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a>";
            display_children($row['id'], $level + 1);
            echo "</li>";
        } elseif ($row['Count']==0) {
            echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>";
        } else;
    }

    echo "</ul>";
}