Skip to content
Advertisement

PHP/SQL Dynamic menu depending on different tables

I’m trying to manage a dynamic menu based on results from tables in my database.

Code below is so far i have come.. But i can’t get it to display as i want to.

i have 3 tables in my database looking like this.

ws_categories

  • id
  • maincat (name of main-category)

ws_subcategories

  • id
  • subcat (Name of sub-category)
  • parentcat (id of main-category)

ws_subsubs

  • id
  • subsub (Name of 2nd-sub-category)
  • parentsub (id of sub-category)

What i want to achieve? Having a simple vertical menu, that outputs main categories, and onclick, submenue alternatives related to that main category will show, if a sub category has a 3rd submenu/submenues, they will show under..

Code below is so far i have come.. But i don’t seem to understand why it output main category several times and not just once..

To be clear, i do not understand how i should use join to achieve this. I want to be able to echo all main categories once, and subcategories once, and if there is one or more 2nd sub categories i want them to echo too.. How do i achieve this with join? is it even possible or am i looking the wrong way?

Thanks in advance.

PHP

JavaScript

Javascript

JavaScript

CSS

JavaScript

Advertisement

Answer

Your SQL request will give you for each main category as many rows as it has sub categories:

JavaScript

You could make a request to select all maincats, and for each maincat, make another request to select all its subcats. Something like this:

PHP

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement