我如何通过php&添加菜单子项MYSQL

时间:2014-09-04 04:02:05

标签: php mysql

我已经进行了动态导航,但现在我想在父菜单中插入子项 例如:如果我插入父菜单,那么就可以在其中插入子菜单。

<?php    
include("includes/db.php");  

$query="select * from menus";  

$run=mysql_query($query);  

while($row=mysql_fetch_array($run)){  

    $m_title = $row[1];

    echo "<ul><li><a href='pages.php?pages=$m_title'>$m_title</a></li></ul>";
}

?>

2 个答案:

答案 0 :(得分:0)

如果要为应用程序创建n级菜单,则需要递归函数。

首先在表中添加“parent”id字段:

    CREATE TABLE IF NOT EXISTS `menus` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `parent` int(11) NOT NULL DEFAULT '0',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

    INSERT INTO `menus` (`id`, `title`, `parent`) VALUES
    (1, 'Menu 1', 0),
    (2, 'Menu 2', 0),
    (3, 'Sub Menu 1', 1),
    (4, 'Sub Menu 2', 1),
    (5, 'Sub Menu 3', 2);

并使用以下函数生成n级菜单:

    createmenu(0); // Enter root menu id

    function createmenu($pid) {

       if($pid == 0) { echo "<ul>"; }

       $query = "select * from menus where parent = $pid";
       $run = mysql_query($query);         
       $count = mysql_affected_rows();

       if($count > 0) {

           echo "<ul>";

           while($row=mysql_fetch_array($run)){  

                $id = $row[0];
                $m_title = $row[1];

                echo "<li><a href='pages.php?pages=$m_title'>$m_title</a>";

                $q = "select * from menus where parent = $id";
                $r = mysql_query($q);          
                $c = mysql_affected_rows();

                if($c > 0) {
                    createmenu($id);
                }

                echo "</li>";               
            }   

            echo "</ul>";      
       }

       if($pid == 0) { echo "</ul>"; }
    }

你会得到以下输出:

<ul>
    <ul>
        <li><a href='pages.php?pages=Menu 1'>Menu 1</a>
            <ul>
                <li><a href='pages.php?pages=Sub Menu 1'>Sub Menu 1</a></li>
                <li><a href='pages.php?pages=Sub Menu 2'>Sub Menu 2</a></li>
            </ul>
        </li>
        <li><a href='pages.php?pages=Menu 2'>Menu 2</a>
            <ul>
                <li><a href='pages.php?pages=Sub Menu 3'>Sub Menu 3</a></li>
            </ul>
        </li>
    </ul>
</ul>

答案 1 :(得分:0)

$conn = new mysqli('localhost', 'root', '') or die('connection error');
mysqli_select_db($conn, $dbhandle) or die("Could not select examples");

$menu = '';
$data = display_children(0, $conn, $menu);

function display_children($level = 0, $conn, &$menu)
{
    $result = mysqli_query($conn, "select * from menu where parent_id=$level");
    $menu.= "<ul class='nav'>";
    while ($row = mysqli_fetch_array($result)) {
        $menu.= "<li class='has-submen'><a href='#'>" . $row['menu_name'] . "</a>";
        display_children($row['id'], $conn, $menu);
        $menu.= "</li>";
    }
    $menu.= "</ul>";
}

echo $menu;