There are lots of scripts, free or not, that provide for this. These are very tricky, and I recommend you find one to modify, not build from scratch.
Nearly all these scripts, to some extent, depend on Javascript.
What you will need to do then, is use PHP/SQL to output Javascript, or modifications to Javascript.
This is fairly easy to do, but it is a king hell bitch to debug. It is particularly hard when you need to create an elaborate datastructure for dynamic hierachical menus. I speak for bitter experience.
My advice is to menus of as little depth as possible:
Top Menu>Bottom menu1, bottom menu2, bottom menu 3
Not:
Top Menu>mid menu 1>lower menu 1>Bottom menu1, bottom menu2, bottom menu 3
lower menu 2>Bottom menu 4, bottom menu 5
mid menu 2>Lower menu 3>Bottom menu6
etc..
If possible.
Also when choosing the script you plan to use, be sure to check that
menu label elements
and
style elements
are indiividually isolated and called out, not embedded in the Javascript.
Good luck.