2014-09-04 40 views
0

我已經做了一個動態導航,但現在我想在我的父菜單中插入子項
例如:如果我插入一個父菜單,然後可以插入子項。我是如何通過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>"; 
} 

?> 

回答

0

如果要爲應用程序創建n級菜單,則需要遞歸功能。

先加 「父」 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> 
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;