To present bulk of data with parent child relationship Treeview is a classical approach. The major advantage of Treeview is using a Treeview we can show more data in less space. Assume that you have a global recruitment portal. You want to display job opportunities depending upon Countries and their Cities. In this case you required a Treeview.
Using a Treeview easily you can display Countries & related Cities hirarchically. In this session let us share sample codes for a PHP Treeview using data from MySQL Database. In front-end using PHP I am binding data to ol li element of HTML. Then by applying CSS styles giving expand and collapse effects to the Treeview. Let us explain this PHP Treeview Example Step by Step.
1. Create a MySQL table “tab_treeview”. Consider “id” as the Primary key. During an user enter a record to this SQL table I need the primary field entry need to jump 1 after 1 automatically. Thats why here I declared id filed with “auto_increment” property. To store Treeview node details Create 2 other Columns name and title. These fields are with datatype varchar(255). While inserting records keep noted these fields will accept only 255 charecters. You can’t entry a null value to these fields as NOT NULL attributes specifies. Then to establish parent child relationship created one more column “parent_id”. This will store reference of parent node. If parent_id is zero then that record is itself a parent node.
Query to Create table tab_treeview
CREATE TABLE IF NOT EXISTS tab_treeview ( id int(12) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, title varchar(255) NOT NULL, parent_id varchar(12) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7;
2. To start with first you need to insert some sample records to “tab_treeview” SQL table. While inserting sample records stay careful about parent_id. A wrong parent_id can change your Treeview structure and nodes.
Query to Insert sample Records
INSERT INTO tab_treeview (id, name, title, parent_id) VALUES (1, 'Mumbai', 'The Film City', '3'), (2, 'New Delhi', 'Capital of India', '3'), (3, 'India', 'Country', '0'), (4, 'United States', 'Country', '0'), (5, 'Washington', 'Popular City of US', '4'), (6, 'New York', 'Popular City of US', '4'), (7, 'Olympia', 'Capital of Washington', '5'), (8, 'Russia', 'Country', '0'), (9, 'Moscow', 'Popular City of Russia', '8'), (10, 'Saint Petersburg', 'Popular City of Russia', '8') (11, 'Bihar', 'State of India', '3'), (12, 'Uttar Pradesh', 'State of India', '3'), (13, 'Himachal Pradesh', 'State of India', '3');
PHP Treeview Example (Binding Data from Database)
3. Create a blank HTML page. Then in body inside PHP tag Copy n Paste the below recursive function “buildTree()”. Keep notice this is the function which generates Treeview html. In this function using a foreach loop I am dealing each record from the database. Then dynamically using HTML5 ol li and echo function from PHP writing the ordered list as a treeview.
buildTree() Recursive function
This approach is often used to break down complex problems into simpler subproblems, allowing for easier management and resolution. When implementing a recursive function, it is essential to define a base case to prevent infinite loops and ensure that the function eventually terminates. Additionally, careful consideration of the function’s parameters and return values is crucial for maintaining clarity and efficiency in the code.
function buildTree($array, $currentParent, $currLevel = 0, $prevLevel = -1) { foreach ($array as $categoryId => $category) { if ($currentParent == $category['parent_id']) { if ($currLevel > $prevLevel) echo "<ol id='menutree'>"; if ($currLevel == $prevLevel) echo "</li>"; echo '<li> <label class="menu_label" for='.$categoryId.'>'.$category['name'].'</label><input type="checkbox" id='.$categoryId.' />'; if ($currLevel > $prevLevel) { $prevLevel = $currLevel; } $currLevel++; buildTree ($array, $categoryId, $currLevel, $prevLevel); $currLevel--; } } if ($currLevel == $prevLevel) echo "</li> </ol>"; }
Using the recursive function buildTree() inside a foreach loop over $array length I am building each li element of ordered list. To position the cursor for next item here I am using $currLevel++ increment operator. Here orderlist id is “menutree”.
4. Below the “buildTree()” function Copy n Paste the below PHP codes. Here using this block I am fetching data from tab_treeview table.
Understanding the Structure of a Treeview
A treeview is a hierarchical data structure that organizes information in a parent-child relationship, resembling an inverted tree. It is widely used in computer science, databases, file systems, and user interfaces to represent nested data efficiently. The structure consists of nodes, each serving a specific role in the hierarchy. The four primary components of a treeview are the root node, parent node, child node, and leaf node. Understanding these elements is essential for working with tree-like data models.
The Root Node
The root node is the topmost element in a treeview hierarchy. In a file system, for example, the root directory (often represented as “/” in Unix-based systems or “C:\” in Windows) is the root node. All files and subdirectories stem from this single point.
A key characteristic of the root node is that it is always singular in a well-formed tree structure. Multiple root nodes would imply separate trees, often referred to as a forest in data structure terminology. The root node’s primary function is to provide a reference point for traversing the hierarchy, allowing algorithms to navigate downward through parent and child relationships.
Parent Nodes
A parent node is any node in the treeview that has one or more child nodes connected beneath it. Parent nodes act as containers for their children, grouping related data into meaningful subsets. For instance, in an organizational chart, a department head (parent node) may oversee several team leads (child nodes), who in turn manage individual employees.
Parent nodes can themselves be children of higher-level parents, creating multiple layers of depth in the tree. The ability to collapse or expand parent nodes in a graphical user interface (GUI) enhances usability by allowing users to hide or reveal details as needed.
Child Nodes
Child nodes are direct descendants of a parent node. Each child node can have only one immediate parent, ensuring a clear hierarchical relationship. Child nodes inherit certain properties from their parents, such as access permissions in a file system or organizational roles in a management hierarchy.
A child node may also function as a parent if it has its own descendants, creating a multi-level tree structure. For example, in a product category tree, “Electronics” might be a child of the root node, while “Smartphones” is a child of “Electronics,” and “Brand X” is a child of “Smartphones.” This chaining of relationships allows for detailed and scalable data organization.
Leaf Nodes
They represent the most granular level of data in the hierarchy. In a file system, individual files are leaf nodes, whereas directories act as parent nodes. Similarly, in a family tree, individuals without descendants would be considered leaf nodes.
Leaf nodes often contain actionable or displayable data, such as file contents in a directory, employee names in an org chart, or product details in an e-commerce category tree. Their position at the end of branches makes them crucial for data retrieval operations, as they hold the actual information rather than just structural references.
Understanding the structure of a treeview—comprising root nodes, parent nodes, child nodes, and leaf nodes—is fundamental for efficient data organization and retrieval. This hierarchical model provides clarity, scalability, and flexibility, making it indispensable in various fields. Whether navigating file systems, designing databases, or structuring user interfaces, recognizing the roles of each node ensures optimal system performance and usability. Mastery of treeview principles empowers users and developers to harness the full potential of hierarchical data representation.
Treeviews can be rendered using HTML, CSS, and JavaScript, with PHP handling the backend logic to fetch and structure the data.
Traversal Techniques
Navigating a treeview involves moving from one node to another using specific algorithms. The two primary traversal methods are:
1. Depth-First Search (DFS): Explores as far down a branch as possible before backtracking. Variations include in-order, pre-order, and post-order traversals.
2. Breadth-First Search (BFS): Visits nodes level by level, starting from the root and moving downward in layers.
Fetching data from MySQL Database
As natural first using mysql_connect I am pointing my PHP Compiler to localhost mysql database as the user root. In next step using mysql_select_db pre-defiend php function I am selecting treeview specific database from MySQL server. Now we need to execute the sql query “SELECT * FROM tab_treeview” to fetch data from db. To do that using mysql_query and storing all records to an array $arrayCountry.
/*Connecting to Database tempdb*/ mysql_connect('localhost', 'root'); mysql_select_db('tempdb'); /*Executing the select query to fetch data from table tab_treeview*/ $sqlqry="SELECT * FROM tab_treeview"; $result=mysql_query($sqlqry); /*Defining an array*/ $arrayCountry = array(); while($row = mysql_fetch_assoc($result)){ $arrayCountry[$row['id']] = array("parent_id" => $row['parent_id'], "name" => $row['name']); } /*Checking is there any records in $result array*/ if(mysql_num_rows($result)!=0) { /*Calling the recursive function*/ buildTree($arrayCountry, 0); }
Finally on array of data using while loop to build the tree. Inside while loop after checking data persist for the existing row calling the recursive function buildTree($arrayCountry, 0);. Where the first parameter is the $arrayCountry. The function buildTree() accepts 4 parameters. Using this you can customize your treeview as needed.
5. Now you can able to watch Treeview data in your html page. Apply the below CSS styles to implement expand and collapse effects. Add a style tag in html file head section and copy the below CSS styles. To customize this dynamic Treeview including the below classes you can add your additional CSS Classes.
CSS Styles for PHP Treeview
To remove default bulleted list from my ordered list items here I am using list-style: none; for my menu menutree. On clickable node of tree to my the cursor with hand symbol here I am using cursor: pointer for all menu labels.
#menutree li { list-style: none; } li .menu_label + input[type=checkbox] { opacity: 0; } li .menu_label { cursor: pointer; } li .menu_label + input[type=checkbox] + ol > li { display: none; } li .menu_label + input[type=checkbox]:checked + ol > li { display: block; }
Security Considerations
Modern web applications face numerous security threats that can compromise user data, disrupt services, and damage organizational reputations. Three critical vulnerabilities—SQL Injection, Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF)—pose significant risks if not properly mitigated. Understanding these threats and implementing protective measures is essential for maintaining a secure digital environment.
SQL Injection
By inserting malicious SQL queries into input fields, attackers can manipulate or extract sensitive data, bypass authentication, and even execute administrative operations.
Prevention Techniques
1. Parameterized Queries (Prepared Statements) Using parameterized queries ensures that user input is treated as data rather than executable code. Most modern database libraries support this method.
2. Input Validation Restrict input to expected formats (e.g., alphanumeric characters only) and reject suspicious patterns (e.g., SQL keywords).
3. Stored Procedures Encapsulate database logic in stored procedures, reducing direct SQL string manipulation.
4. Least Privilege Principle Database accounts should have minimal permissions necessary for the application, limiting damage in case of a breach.
Cross-Site Scripting (XSS) Prevention
Cross-Site Scripting (XSS) happens due to the injection of malicious scripts. These scripts can steal session cookies, deface websites, or redirect users to phishing sites.
Types of XSS
1. Reflected XSS Malicious scripts are embedded in URLs or forms and executed when the victim loads a manipulated link.
2. Stored XSS Attackers inject persistent scripts into a database or file, which are later served to users.
3. DOM-Based XSS Scripts manipulate the Document Object Model (DOM) directly in the victim’s browser without server interaction.
Prevention Techniques
1. Output Encoding Encode dynamic content before rendering it in HTML, JavaScript, or other contexts to neutralize malicious scripts.
2. Content Security Policy (CSP) Define a CSP header to restrict sources of executable scripts, reducing the impact of XSS attacks.
3. Input Sanitization Remove or escape unsafe characters (e.g., `<`, `>`, `&`) from user-generated content.
4. HTTP-Only Cookies Mark session cookies as HTTP-only to prevent JavaScript access, mitigating cookie theft.
CSRF Protection
Cross-Site Request Forgery (CSRF) tricks users into executing unintended actions on a web application where they are authenticated. Attackers exploit the trust between a user’s browser and a legitimate website to submit forged requests.
Prevention Techniques
1. Anti-CSRF Tokens Require a unique, unpredictable token with each state-changing request. The token must match the one stored on the server.
2. SameSite Cookies Set the `SameSite` attribute for cookies to `Strict` or `Lax` to prevent cross-origin requests.
3. Double-Submit Cookies Store the CSRF token in both a cookie and a hidden form field, validating both upon submission.
4. Require Re-Authentication For sensitive actions (e.g., password changes), force users to confirm their credentials again.
Security threats like SQL Injection, XSS, and CSRF require proactive measures to prevent exploitation. Developers must adopt secure coding practices, validate and sanitize input, implement robust authentication mechanisms, and stay updated on emerging threats. By prioritizing security, organizations can safeguard user data and maintain trust in their digital services.
Performance Optimization
Lazy Loading – This approach enhances performance and reduces resource consumption, particularly in web applications where numerous elements may be present. Load only visible nodes.
Indexing – Ensure `parent_id` is indexed for faster queries.
Real-World Applications
Treeview is a useful tool that helps us organize information in a way that is easy to understand. Imagine you have a big box of toys. If you just dump them all out, it can be hard to find what you want. But if you sort them into groups—like cars in one section and dolls in another—it becomes much easier. In the real world, treeviews are used in many places, like on websites or apps. For example, when you look at files on a computer, the treeview shows folders and files in a clear way. This helps you find what you need quickly. Treeviews are also used in educational apps to break down topics into smaller parts, making learning simpler and more fun. Overall, treeviews help people manage and find information more easily, just like organizing your toys!
1. File Managers – Display directories and files.
2. E-Commerce Categories – Organize product hierarchies.
3. Navigation Menus – Create multi-level dropdowns.
Conclusion
A PHP treeview is a powerful tool for displaying hierarchical data in a structured and interactive manner. By combining PHP for backend logic, HTML/CSS for presentation, and JavaScript for interactivity, developers can create efficient and user-friendly treeviews. Whether used in file systems, navigation menus, or organizational charts, mastering treeview implementation enhances web application usability and functionality.