In this tutorial, We will learn how to create a treeview with the JStree plugin in PHP. We will create a folder structure using the jsTree plugin and PHP. I will show you the folder Treeview structure using the PHP and jsTree plugin.
Example;
Create database table folders
CREATE TABLE `folders` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`sub_folder_id` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Then insert some dummy data as folder name
connect to database config.php
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* Username */
$password = ""; /* Password */
$dbname = "new_blog"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
Create index.php file and put the following code . include config.php file to connect database then include jstree plugin too via CDN link.
index.php
<?php
include "config.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP - Create Treeview using jsTree Example</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)) {
$subFolder = $row['sub_folder_id'];
if ($subFolder == '0')
$subFolder = "#";
$selected = false;
$opened = false;
if ($row['id'] == 2) {
$selected = true;
$opened = true;
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $subFolder,
"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>
<script type="text/javascript">
$(document).ready(function () {
var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());
$('#folder_jstree').jstree({'core': {
'data': folder_jsondata,
'multiple': false
}});
});
</script>
</body>
</html>
Thanks, May this example will help you.