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.
Table of Content
- Create a Table and Insert Data
- Create Database Connection file
- Download & Include jstree plugin
- HTML & PHP – Create Layout for jsTree
- jQuery – Initialize jsTree
- Demo
- Conclusion
1. Create a Table and Insert Data
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. Create Database Connection file
Create config.php
for the database connection.
<?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 jsTree plugin
- 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 – Create Layout for jsTree
Fetch all records from folders
table and loop on it.
Here’s what the data should look like in a JSON format for jsTree setup:
{ "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 it into JSON format.
- If the
$parent_id
equals 0, set$parent_id
to ‘#’. - If you want to select and open a node with an ID of 2, set the
$selected
and$opened
variables to true. - Start by initializing an
$folders_arr
Array with keys: id, parent, text, and state. - 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 – Initialize jsTree
Read Data:
Retrieve the data from the #txt_folderjsondata
element. This data will be in JSON format.
Convert to JSON Object:
Convert the data into a JSON object and store it in folder_jsondata
variable .
Initialize jsTree:
Set up the jsTree plugin on the #folder_jstree
element.
Core Data Option:
Configure the jsTree’s core data option. Use the folder_jsondata
as the data source.
Disable Multiple Selection:
Make sure that users can’t select multiple nodes simultaneously by setting the multiple
option 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.
Remember, it’s essential to provide the JSON data in the correct format; otherwise, the initialization won’t work.
If you found this tutorial helpful then don't forget to share.