How to create dynamic menu and submenu using php and mysql

Hi
all

This is samiuddin. I am new to php. I have given a task to create menu and sub menu using php and mysql.

I created a table with the following fields.

  1. ID (autogenerated)
    2.menuname
  2. parentID
  3. link

i inserted the data like this

Id =1
menu name= booking
parentid=0
link=index.php

id=2
menu name = new
parentid=1
link=newform.php

booking is the main menu and new is the submenu of booking

now how to call this in the php

Thanks

before starting the code of menu and sub menu, search that type of ready code in Google. It very much helpful to make your program.

The easy way for now could be use two queries:

  • Select all menus which has parent_id=0
    (SELECT * FROM tblmenu WHERE parentid=0)
  • Loop through the result and again select the menus having the parent_id=PARENT_MENU
    (SELECT * FROM tblmenu WHERE parentid=parent_menu_id)

Hope you can manage the PHP code.

The easy way for now could be use two queries:

  • Select all menus which has parent_id=0
    (SELECT * FROM tblmenu WHERE parentid=0)
  • Loop through the result and again select the menus having the parent_id=PARENT_MENU
    (SELECT * FROM tblmenu WHERE parentid=parent_menu_id)

Hope you can manage the PHP code.

This is correct way.

looping while the condition matches in the parent list…

thanks i will try it out and get back to you

once again thanks for your early response


$resultMainMenu = mysql_query("SELECT * FROM tblmenu WHERE parentid=0 ORDER BY menuname ASC") or die(mysql_error());
while($row = mysql_fetch_array($resultMainMenu)){
    echo $row['menutitle'] . '<br />'; // echo main menu
    $resultSubmenu = mysql_query("SELECT * FROM tblmenu WHERE parentid=" . $row['id'] . " ORDER BY menuname ASC") or die(mysql_error());
    if(mysql_num_rows($resultSubmenu) >= 1){
        while($rowSub = mysql_fetch_array($resultSubmenu)){
            echo ' -- ' . $rowSub['menutitle'] . '<br />'; // echo sub menu
        }
    }
}