Php

Treeview using Bootstrap Treeview, PHP and MySQL

I got huge response of treeview tutorials How to Create Dynamic Tree View Menu from readers and find request to create bootstrap treeview using php and mysql. This treeview menu tutorials help to create beautiful tree menu using bootstrap 3, php and mysql. I will create JSON data from mysql table data which are containing parent and child relation as mentioned my previous tutorials.

I have found Bootstrap treeview plugin to create tree view menu using bootstrap 3. Bootstrap treeview is very simple and elegant solution to displaying hierarchical tree structures using bootstrap.

This tutorials will use following dependencies

  • Bootstrap v3.3.4 (>= 3.0.0)
  • jQuery v2.1.3 (>= 1.9.0)
  • PHP(>= 5.2.0)
  • MySQL(>= 5.3.0)

As bootstrap treeview described in his docs, we need to create a nested JavaScript JSON object which will contains all nodes information with all options.We need to define following types JSON Object to create the hierarchical structure.

var tree = [
  {
    text: "Parent 1",
    nodes: [
      {
        text: "Child 1",
        nodes: [
          {
            text: "Grandchild 1"
          },
          {
            text: "Grandchild 2"
          }
        ]
      },
      {
        text: "Child 2"
      }
    ]
  },
  {
    text: "Parent 2"
  },
  {
    text: "Parent 3"
  },
  {
    text: "Parent 4"
  },
  {
    text: "Parent 5"
  }
];

Where as:
text : this will use for display node name/label.
node[] : This array will contains all children nodes of parent node.

We can define all properties or options on nodes eg.bg-image,color etc with each nodes as like below,

{
  text: "Node 1",
  icon: "glyphicon glyphicon-stop",
  selectedIcon: "glyphicon glyphicon-stop",
  color: "#000000",
  backColor: "#FFFFFF",
  href: "#node-1",
  selectable: true,
  state: {
    checked: true,
    disabled: true,
    expanded: true,
    selected: true
  },
  tags: ['available'],
  nodes: [
    {},
    ...
  ]
}

As you can see to above single json object, You can customized your node very easily using above json properties.There are number of options available to create custom option.

You can also check other tutorial of TreeView Menu,

How To create Dynamic Tree using Bootstrap Treeview,PHP and MySQL

So we are using below files to create dynamic treeview structure using bootstrap jquery tree plugin, php and mysql. Its very easy and simple,The project structure are follows,

  1. index.php : This file is use to display tree
  2. response.php : This file is use to fetch tree nodes from database and convert them into json object.

Create Database Table and Connection Using PHP and MySQL

First we will create database connection to get table nodes from mysql using php.I am assuming you have 'test', if you dot have please create new database and fill name 'test'.

Step 1: Create Table structure to stored tree menu nodes.

Related Post
CREATE TABLE IF NOT EXISTS `treeview_items` (
`id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `label` varchar(200) NOT NULL,
  `parent_id` varchar(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Step 2: Create connection string using php with mysql in (response.php) file.We have passed $servername, $username, $password and $dbname parameters to mysql connection object.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

Step 3: Included all js/css files of bootstrap treeview into index.php file.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script>

Step 4: Created tree menu container in index.php.

<div id="treeview_json"></div>


Step 5: We will use ajax request to get JSON data from php server side.I will use GET type Ajax request and passed json data to bootstrap treeview method.

<script type="text/javascript">
$(document).ready(function(){ 
    $.ajax({
   type: "GET",  
   url: "response.php",
   dataType: "json",       
   success: function(response)  
   {
  initTree(response)
   }   
 });
});
</script>

Step 6: We will call bootstrap treeview method on div container where we want to render hierarchical structure.The container id is '#treeview_json'.

<script type="text/javascript">
$(document).ready(function(){ 
    $('#treeview_json').treeview({data: treeData});
});
</script>

Now we will work on server side using PHP,I will create response.php file which are used in above AJAX request.We will create connection string with mySQL as stated in Step 2.

We will get all nodes information from MySQL rather than Constant JSON and set node options as we needed to bootstrap treeview JSON node, finally we will create JSON hierarchical structure as need for bootstrap treeview.

Step 7: created PHP array of all tree nodes and encode into json(response.php).

$sql = "SELECT * FROM `bootstrap_treeview_nodes` ";
 $res = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
  //iterate on results row and create new index array of data
  while( $row = mysqli_fetch_assoc($res) ) { 
   $tmp = array();
   $tmp['id'] = $row['id'];
   $tmp['name'] = $row['name'];
   $tmp['text'] = $row['label'];
   $tmp['parent_id'] = $row['parent_id'];
   $tmp['href'] = $row['link'];
   array_push($data, $tmp); 
  }
  $itemsByReference = array();

 // Build array of item references:
 foreach($data as $key => &$item) {
    $itemsByReference[$item['id']] = &$item;
    // Children array:
    $itemsByReference[$item['id']]['nodes'] = array();
 }

 // Set items as children of the relevant parent item.
 foreach($data as $key => &$item)  {
 //echo "

<pre>";print_r($itemsByReference[$item['parent_id']]);die;
    if($item['parent_id'] && isset($itemsByReference[$item['parent_id']])) {
       $itemsByReference [$item['parent_id']]['nodes'][] = &$item;
  }
 }

Conclusion :

I have created treeview menu using bootstrap treeview plugin.Its very easy to use and more customizable options available for tree view node.I used PHP and MySQL to get JSON tree nodes data from server side and parse json as required for bootstrap treeview JSON data.

You can download source code and Demo from below link.

View Comments

Recent Posts

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

2 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

2 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

2 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

3 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

3 months ago

Common Practices for Laravel Blade Template

in this Laravel tutorial, I will explore common practices for using the Laravel Blade template with examples. Blade is a… Read More

3 months ago

Categories