If you already managing the relationship between parent and child items using a separate field then it is easier to create a hierarchical structure.
With the use of a jsTree plugin, this will be created in less time.
jsTree is a jQuery plugin that creates a hierarchical data structure using JSON data.
It allows setting icon of a node, by default open, disable a node and set it selected while initializing, etc.
In this tutorial, I show how you can make a tree structure of MySQL data using jsTree plugin and PHP.
Contents
1. Table
I am using folders
table in the example –
CREATE TABLE `folders` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL, `parentid` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
It has the following data –
INSERT INTO `folders` (`id`, `name`, `parentid`) VALUES (1, 'Folder1', 0), (2, 'Folder2', 0), (3, 'Folder 1 sub1', 1), (4, 'Folder 1 sub1.1', 3), (5, 'Folder 1 sub1.2', 3), (6, 'Folder 1 sub1.1.1', 4), (7, 'Folder 1 sub2', 1), (8, 'Folder 1 sub3', 1), (9, 'Folder 1 sub3.1', 8), (10, 'Folder 2 sub1', 2), (11, 'Folder 2 sub1.1', 10), (12, 'Folder 2 sub1.2', 10), (13, 'Folder 2 sub2', 2), (14, 'Folder 3', 0);
I stored parent id value in parentid
field.
2. Configuration
Create a config.php
for the database connection.
Completed Code
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. Download & Include
- Download the jsTree plugin from the official website.
- Include jsTree style.min.css, jQuery library, and jstree.min.js file.
<link rel="stylesheet" type="text/css" href="jstree/dist/themes/default/style.min.css"> <script src="jquery-3.4.1.min.js"></script> <script type="text/javascript" src="jstree/dist/jstree.min.js"></script>
Or you can use CDN –
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
4. HTML & PHP
Fetch all records from folders
table and loop on it.
JSON data syntax –
{ "id": [id], "parent": [parentid], "text": [text], "state": { "selected": [boolean-value], "opened": [boolean-value] } }
NOTE – If parent id is 0 then pass ‘#’.
With PHP create an Array and encode in JSON format.
If $parentid
is equals to 0 then assign ‘#’ to $parentid
.
For setting a node with $id == 2
selected and opened pass true
to $selected
and $opened
variables.
Initialize $folders_arr
Array with id
, parent
, text
, and state
keys.
Create <div id='folder_jstree'>
to initialize jsTree and <textarea id='txt_folderjsondata' >
to store $folders_arr
Array in JSON format.
Completed Code
<?php include "config.php"; ?> <!DOCTYPE html> <html> <head> <title>Create Treeview with jsTree plugin and PHP</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script> </head> <body> <?php $folderData = mysqli_query($con,"SELECT * FROM folders"); $folders_arr = array(); while($row = mysqli_fetch_assoc($folderData)){ $parentid = $row['parentid']; if($parentid == '0') $parentid = "#"; $selected = false;$opened = false; if($row['id'] == 2){ $selected = true;$opened = true; } $folders_arr[] = array( "id" => $row['id'], "parent" => $parentid, "text" => $row['name'], "state" => array("selected" => $selected,"opened"=>$opened) ); } ?> <!-- Initialize jsTree --> <div id="folder_jstree"></div> <!-- Store folder list in JSON format --> <textarea id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea> </body> </html>
5. jQuery
Read value from #txt_folderjsondata
and convert it into a JSON object and assign in folder_jsondata
.
Initialize jstree on #folder_jstree
.
Pass folder_jsondata
in core
data
option. Using multiple
option disable multiple node selection by setting it to false
.
Completed Code
$(document).ready(function(){ var folder_jsondata = JSON.parse($('#txt_folderjsondata').val()); $('#folder_jstree').jstree({ 'core' : { 'data' : folder_jsondata, 'multiple': false } }); });
6. Demo
7. Conclusion
If parentid
is equaled to 0 then assign ‘#’ to parent key.
You need to pass JSON data in a specified format otherwise it will not initialize.
If you found this tutorial helpful then don't forget to share.
Hello my friend and thanks for this tutorial, I have question and a problem unfortunately….
I’ve tried to decode in jSon an associative array I’ve created from a web service and for some reason the resulted jSon is not formed well as the one in this tutorial and demo.
Why ?
this is my PHP array produced from an HTML string:
$new_string = explode(‘|’,$html_val->nodeValue);
//$str = “9|Engineering”; // $re = explode(‘|’, $str); // echo $re[1];//Engineering
$padre = $new_string[0]; //echo ‘padre: ‘.$padre.”;
$figlio = $new_string[1]; //echo ‘figlio: ‘.$figlio.”;
$desc = $new_string[2]; //echo ‘desc: ‘.$desc.”;
$colore = $new_string[3]; //echo ‘colore: ‘.$colore.”;
$lt = $new_string[4]; //echo ‘lt: ‘.$lt.”;
$pallino = $new_string[5];
$magazz = $new_string[6]; //echo ‘magazzino: ‘.$magazz;
$trenino[‘parent’][] = $new_string[0];
$trenino[‘id’][] = $new_string[1];
$trenino[‘name’][] = $new_string[2];
$trenino[‘colore’][] = $new_string[3];
$trenino[‘lt’][] = $new_string[4];
$trenino[‘pallino’][] = $new_string[5];
$trenino[‘magazz’][] = $new_string[6]
and this is part of my jSon produced from json_encode($trenino) :
{“parent”:[“”],”id”:[“MY00027770096″],”name”:[“REJANE 85MM BOTTONE E CHIAVE “],”colore”:[“50FF15″],”lt”:[“0″],”pallino”:[“”],”magazz”:[“NP”]}
Great Tutorial, worked for me in one, thanks man, you are the best. Nice!!!!
You’re welcome.
Buen tutorial y bien compartido, no tiene pérdida. Felicitaciones. Gracias
Wow, this jQuery tree works very well.
I was wondering if it’s possible for me to detect the specific node I’ve (control) clicked on and obtain the associated $row[‘id’]…and perhaps save that in a php session variable. I’d like ot save the selected tree node value so that I can use that value in my code somwehere else. I can’t figure out how to do this.
Thanks!
Binit