You simply define your menu in the $nav variable, and the following PHP automatically sees if the current page matches the link, if so it adds class="active" to the a link. Using the class of active you can then style that link differently, making it clear the user is currently on that page.
Full Answer
See more
Create a dynamic menu in PHP from your MySQL data
Next I have to add some data for our PHP menu: menu items and sub-menu items. Example: The menu item “Products” will have several sub-menu items and the record id is a “2” All sub-menu items need the number “2” as value for the parent_id. The parent_id for each main menu item is a “0” (zero).
Put all the PHP code into a single function
For the creation of the whole navigation bar I a custom function, this way it’s more portable and I can access the code several times in different scripts without to write the code all over again.
A PHP function which is used to manipulate the query string
The code block begins with a test for $_GET variable which is posted via the link from the parent menu item a new loop is opened to create a list with sub-items related to the parent item. Inside the statement the function rebuild_link () is called, a function which is used to manipulate the query string:
Example PHP dynamic menu usage
How to use this dynamic menu PHP function? It’s easy just echo the function name with all the function attributes:
DYNAMIC MENU IN PHP MYSQL
All right, let us now get into the example of creating a dynamic menu with PHP and MYSQL.
USEFUL BITS & LINKS
That’s it for the dynamic menu, and here are some small extras that you may find useful.
THE END
Thank you for reading, and we have come to the end of this tutorial. I hope that it has helped you to create a better menu for your website. If you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!
Creating The Menu
My solution was a mix of several menus i found online. I decided to use a flat table and a simple recursive php function. The first step is working out the table structure. Here is a look at the table i used.
The MySQL Table
The id is you Primary Key field here, followed by label and link being the name and action of the option. The parent will be the id of the parent menu item and finally the sort field is used if you want any control over the order of your menu items.
Styling The Menu
Now after all that it doesnt look like much yet. But im gonna show you how to make this into a horizontal dropdown menu although you could use this to make any sort of menu type.