Search code examples
phpselectmenumysqliparent

MySQLi - select sub menu item from db if parentid same as top menu item id


I have a menu with top and sub items. All the items, top and sub items have a unique "id" in the database and a "parentid". Top items, all have "parentid" "0" as value, sub items have "parentid" same as the "id" of the top item they correspond to..

Is there a way to select the menu from the db to look like this on the page?

Top Item 1 - My Own Sub Item 1, My Own Sub Item 2, My Own Sub Item 3

Top Item 2 - My Own Sub Item 1, My Own Sub Item 2, My Own Sub Item 3

Top Item 3 - My Own Sub Item 1, My Own Sub Item 2, My Own Sub Item 3

etc.

I am new to databases, I tried everything but I can't get what I want.. Thank you for any help!


Solution

  • You need to have a parent child relation between the top menu and the sub items, so you need to create an extra column in the sub items table, say, main_menu_id, after doing this, you need to assign id of the main menu to the sub menu item in that column.

    Later you will need a nested while loop using PHP and have to fetch the records accordingly.

    /* Loop Top Items Starts
          Loop Inner Items (Fetch Sub Items Having ID Of The Main Item)
       Loop Top Items Ends
    */
    

    1st Query

    SELECT * FROM main_menu;
    

    2nd Query (Nested In While Loop)

    SELECT * FROM sub_menu WHERE main_menu_id = $looped_id;