Dynamic Navigation Tree using PHP Multi-Level Array Source Code

Language

Introduction

In this article, I will show you how to Create a Dynamic Navigation Tree in PHP. This kind of feature might be useful for you for your current or future project especially if you are planning to develop a broad and dynamic website or web application. Here, snippets and a sample web application source code are provided.

What is a Dynamic Navigation Tree?

A Dynamic Navigation Tree is a multi-level navigation that is dynamically displayed in a Tree Style. This feature is commonly found in broad web applications with multiple pages.

Here's a visual example of a Dynamic Navigation Tree:

PHPMyAdmin - Navigation Tree

The example above is the MariaDB PHPMyAdmin Front-end. The dynamic tree navigation is located on the left side.

How to Create a Dynamic Navigation Tree?

To create a Dynamic Navigation Tree in PHP, we can manage the navigation data parent and child using PHP Multi-level Array. By that, we can simply separate the parent navigations from the child navigation without exhausting our database by doing multiple redundant queries.

Example of Creating a Dynamic Navigation Tree using PHP

Let's pretend that we have the following MySQL Schema with Navigation Table Data.

  1. CREATE TABLE `page_list` (
  2. `id` int(30) NOT NULL,
  3. `label` varchar(250) NOT NULL,
  4. `link` text NOT NULL,
  5. `title` text NOT NULL,
  6. `parent_id` int(30) DEFAULT NULL,
  7. `is_new_tab` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0= no , 1= yes',
  8. INSERT INTO `page_list` (`id`, `label`, `link`, `title`, `parent_id`, `is_new_tab`, `created_at`, `updated_at`) VALUES
  9. (1, 'Home', '?page=home', 'Home', NULL, 0, '2022-11-10 11:01:00', '2022-11-10 11:01:21'),
  10. (2, 'Page 1', '?page=main_nav_1', 'Sample Navigation Page #1', NULL, 0, '2022-11-10 11:02:51', NULL),
  11. (3, 'Page 1.1', '?page=main_nav_1_1', 'Page 1.1', 2, 0, '2022-11-10 11:03:33', NULL),
  12. (4, 'Page 1.1.1', '?page=main_nav_1_1_1', 'Page 1.1.1', 3, 0, '2022-11-10 11:21:50', NULL),
  13. (5, 'Page 1.2', '?page=main_nav_1_2', 'Page 1.2', 2, 0, '2022-11-10 11:58:24', NULL),
  14. (6, 'Page 1.1.2', '?page=main_nav_1_1_2', 'Page 1.1.2', 3, 0, '2022-11-10 13:10:45', NULL),
  15. (7, 'External', 'https://www.sourcecodester.com/', 'External Link', NULL, 1, '2022-11-10 13:53:33', NULL);

Next, we need to fetch all the navigation data from the database.

Database Connection

db-connect.php

  1. <?php
  2. $host = "localhost";
  3. $username = "root";
  4. $pw = "";
  5. $db_name = "dummy_db";
  6.  
  7. $conn = new mysqli($host, $username, $pw, $db_name);
  8. if(!$conn){
  9. die('Database connection failed');
  10. }
  11. ?>

Fetching Data

  1. <?php
  2. $nav_sql = "SELECT * FROM `page_list` order by `label` asc";
  3. $nav_qry = $conn->query($nav_sql);
  4. if(!$conn->error){
  5. $qry_count = $nav_qry->num_rows;
  6. $nav_results = $nav_qry->fetch_all(MYSQLI_ASSOC);
  7. /*
  8.   * Listing Navigation Label
  9.   */
  10. $nav_list_by_label = array_column($nav_results, 'label', 'id');
  11.  
  12. /*
  13.   * Listing All parent ID
  14.   */
  15. $nav_parents = array_column($nav_results, 'parent_id');
  16. $nav_parents = array_unique($nav_parents);
  17. $nav_parents = array_filter($nav_parents);
  18. }else{
  19. die("Query Failed! Error: ".$conn->error);
  20. }
  21. ?>

Next, let's pretend we have the following script that builds the complete URL of the web application page

  1. <?php
  2. /**
  3.  * Defining Site URL
  4.  */
  5. if(!defined('site_url'))
  6. define('site_url', 'http://localhost/dynamic_nav_tree/');
  7.  
  8. /**
  9.  * Validating Link whether to add the site url or not
  10.  */
  11.  
  12. function esc_link($link=""){
  13. if(preg_match('/^http:\/\/|^https:\/\//',$link)){
  14. $link = $link;
  15. }else{
  16. $link = site_url.$link;
  17. }
  18. return $link;
  19. }
  20. ?>

Then we will display the dynamic navigation menu using the HTML unordered list tag (ul).

  1. <?php
  2. /**
  3.  * Display Nav Child
  4.  */
  5. function get_child($parent_id = 0){
  6. global $nav_tree;
  7. ?>
  8. <ul class="nav-list-child" data-parent="<?= $parent_id ?>">
  9. <?php if(isset($nav_tree[$parent_id])): ?>
  10. <?php foreach($nav_tree[$parent_id] as $nav): ?>
  11. <li class="nav-item" data-link="<?= esc_link($nav['link']) ?>">
  12. <div class="d-flex w-100">
  13. <a class="col-auto flex-shrink-1 px-2 flex-grow-1 fw-bold w-100 text-decoration-none text-dark" href="<?= esc_link($nav['link']) ?>" <?= $nav['is_new_tab'] == 1 ? "target='_blank'" : '' ?> title="<?= $nav['title'] ?>"><?= $nav['label'] ?></a>
  14. <div class="col-auto">
  15. <div class="dropdown">
  16. <a class="text-dark mx-3" href="#" data-bs-toggle="dropdown" aria-expanded="false">
  17. <i class="fa-solid fa-ellipsis-vertical"></i>
  18. </a>
  19. <ul class="dropdown-menu">
  20. <li><a class="dropdown-item edit" data-id='<?= $nav['id'] ?>' href="#">Edit</a></li>
  21. <li><a class="dropdown-item delete" data-id='<?= $nav['id'] ?>' href="#">Delete</a></li>
  22. </ul>
  23. </div>
  24. </div>
  25. </div>
  26. <?php
  27. if($nav['is_parent'] == 1):
  28. echo get_child($nav['id']);
  29. endif;
  30. ?>
  31. </li>
  32. <?php endforeach; ?>
  33. <?php endif; ?>
  34. </ul>
  35. <?php
  36. return ob_get_clean();
  37. }
  38. ?>
  39. <!-- Navigation ul list -->
  40. <ul id="nav-list">
  41. <?php if(isset($nav_tree[0])): ?>
  42. <?php foreach($nav_tree[0] as $nav): ?>
  43. <li class="nav-item" data-link="<?= esc_link($nav['link']) ?>">
  44. <div class="d-flex w-100">
  45. <a class="col-auto flex-shrink-1 flex-grow-1 fw-bold w-100 text-decoration-none text-dark px-2" href="<?= esc_link($nav['link']) ?>" <?= $nav['is_new_tab'] == 1 ? "target='_blank'" : '' ?> title="<?= $nav['title'] ?>"><?= $nav['label'] ?></a>
  46. <div class="col-auto">
  47. <div class="dropdown">
  48. <a class="text-dark mx-3" href="#" data-bs-toggle="dropdown" aria-expanded="false">
  49. <i class="fa-solid fa-ellipsis-vertical"></i>
  50. </a>
  51. <ul class="dropdown-menu">
  52. <li><a class="dropdown-item edit" data-id='<?= $nav['id'] ?>' href="#">Edit</a></li>
  53. <li><a class="dropdown-item delete" data-id='<?= $nav['id'] ?>' href="#">Delete</a></li>
  54. </ul>
  55. </div>
  56. </div>
  57. </div>
  58. <?php
  59. if($nav['is_parent'] == 1):
  60. echo get_child($nav['id']);
  61. endif;
  62. ?>
  63. </li>
  64. <?php endforeach; ?>
  65. <?php endif; ?>
  66. </ul>

In the above script, you can see that on the main list, I only loop the main navigation, doing so, will result in to display of the main navigation menu. Then using the get_child() function, it will loop all the child menus under their designated parent menu.

For the tree design, you will need to code using the CSS Script. Here, I also provided a sample web application source code that demonstrates the above scripts.

Application Snapshot

Main Page

PHP Dynamic Navigation Tree - Main Page

Navigation Tree Panel

PHP Dynamic Navigation Tree - Navigation Panel

Content Panel

PHP Dynamic Navigation Tree - Content Panel

Technologies

Here are the following technologies used for developing the web application.

  • HTML
  • CSS
  • JavaScript
  • PHP
  • MySQL Database
  • Bootstrap Framework
  • jQuery Library
  • Select2 Library
  • Fontawesome Library

Features and Functionalities

Here are the following features and functionalities of the web application.

  • Add New Navigation Menu
  • List Navigation Menu (Tree View)
  • Edit Navigation Menu
  • Delete Navigation Menu
  • Page Content Panel

The source code was only developed for educational purposes only and not intended commercially. Feel free to download and modify the source code.

How to Run?

Requirements

  • Download and Install any local web server such as XAMPP.
  • Download the provided source code zip file. (download button is located below)

System Installation/Setup

  1. Open your XAMPP Control Panel and start Apache and MySQL.
  2. Extract the downloaded source code zip file.
  3. Copy the extracted source code folder and paste it into the XAMPP's "htdocs" directory.
  4. Browse the PHPMyAdmin in a browser. i.e. http://localhost/phpmyadmin
  5. Create a new database named dummy_db.
  6. Import the provided SQL file. The file is known as dummy_db.sql located inside the source code root folder.
  7. Browse the Web Application in a browser. i.e. http://localhost/dynamic_nav_tree/.

DEMO VIDEO

That's it! I hope this will help you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Enjoy :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Submitted bycuesheet (not verified)on Sun, 02/19/2023 - 17:16

Deleting a parent leaves the children in the database, but they are no longer displayed. The deletion should be extended to the extent that all entries that 'parent_id' corresponds to 'id' are deleted beforehand. Of course, it must also be checked again whether there are other children.

Add new comment