The multilevel category is the collection of infinite nested categories. This means that you can create one or more categories within the parent category to the nth level in the list or option. Even, It looks like the Hierarchical Tree Structure. It is mostly implemented in web applications. Therefore, I have shared the best way to create Multilevel Category in PHP MYSQL.
Developers always need to create a dynamic multilevel nested category in their projects. So, they need to learn it. Even they have many solutions to implement it. But I will learn you in a proper way with the best example. So that you will quickly create a large & complex multilevel category after reading this tutorial.
Also, Read –
Dynamic Category and Subcategory in PHP Using MySQL
Multilevel Category With Tree structure in PHP MySQL
You have to read all the following steps to understand and create a multilevel category in PHP and MySQL. So, You must not skip any one of the given points.
1. Configure Multilevel Category Requirement
First of all, create the following folder structure for testing purposes.
myproject/ |__database.php |__multcatcat-script.php |__user-form.php
Create a database with the name codingstatus
table with the name of categories
in PHPMyAdmin using the following Query.
Table Name – categories
CREATE TABLE `categories` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `parent_id` int(10) DEFAULT 0, `category_name` varchar(255) DEFAULT NULL, );
2. Connect PHP to MySQL Database
You must connect PHP to the MySQL database with its credentials. After that start writing code for creating a multilevel category
File Name – database.php
<?php $hostname = "localhost"; $username = "root"; $password = ""; $databasename = "codingstatus"; // Create connection $conn = mysqli_connect($hostname, $username, $password,$databasename); // Check connection if (!$conn) { die("Unable to Connect database: " . mysqli_connect_error()); } ?>
3. Create a Multilevel category Using PHP
To create a multilevel category, you have to declare the following PHP functions –
- create_category() is declared to insert categories into the database
- multilevel_categories($parent_id=0) is declared to fetch records of all categories from the database.
- display_list($nested_categories) is declared to display multilevel category list on the page
- display_option($nested_categories,$mark=’ ‘) is declared to display categories in the option tag of the select element.
- legal_input($value) is declared to validate the input category before inserting it into the database
File Name – multicat.php
<?php include('database.php'); if(isset($_POST['addcat'])){ $msg=create_category(); } // insert query function create_category(){ global $conn; $parent_id= legal_input($_POST['parent_id']); $category_name= legal_input($_POST['category_name']); $query=$conn->prepare("INSERT INTO categories (parent_id, category_name) VALUES (?,?)"); $query->bind_param('is',$parent_id,$category_name); $exec= $query->execute(); if($exec){ $msg="Category was created sucessfully"; return $msg; }else{ $msg= "Error: " . $query . "<br>" . mysqli_error($conn); } } $catData=multilevel_categories(); function multilevel_categories($parent_id=0){ global $conn; $query = $conn->prepare('SELECT * FROM categories WHERE parent_id=?'); $query->bind_param('i',$parent_id); $query->execute(); $exec=$query->get_result(); $catData=[]; if($exec->num_rows>0){ while($row= $exec->fetch_assoc()) { $catData[]=[ 'id'=>$row['id'], 'parent_id'=>$row['parent_id'], 'category_name'=>$row['category_name'], 'nested_categories'=>multilevel_categories($row['id']) ]; } return $catData; }else{ return $catData=[]; } } function display_list($nested_categories) { $list = '<ul>'; foreach($nested_categories as $nested){ $list .= '<li>'.$nested['category_name'].'</li>'; if( ! empty($nested['nested_categories'])){ $list .= display_list($nested['nested_categories']); } } $list .= '</ul>'; return $list; } function display_option($nested_categories,$mark=' ') { foreach($nested_categories as $nested){ $option .= '<option value="'.$nested['id'].'">'.$mark.$nested['category_name'].'</option>'; if( ! empty($nested['nested_categories'])){ $option .= display_option($nested['nested_categories'],$mark.' '); } } return $option; } // convert illegal input to legal input function legal_input($value) { $value = trim($value); $value = stripslashes($value); $value = htmlspecialchars($value); return $value; } ?>
Now, you can use this code to create any kind of multilevel tree structure. You need not change anything in this code. But It depends on your requirement. If you need to change anything then you can but you have to care that everything will be related to the script.
Don’t forget to include the database connection file multicat.php
4. Display Multilevel Category
In this step, We will create a form to insert category data in the database and a list to display categories in the form of a multilevel tree. So, You have to write code for them according to the following steps –
- First of all, include multicat-script.php
- Create a form with two input fields like select & Text input field and display categories option within the select input field
- After that, display a list in the form of a multilevel category
- Also, write some lines of CSS code to design a multilevel category tree & HTML form.
File Name – user-form
<?php include('multcat-script.php'); ?> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="style.css"> <title>Multilevel Category in PHP</title> </head> <body> <!--====form section start====--> <div class="left-col"> <ul> <li><a href="user-form.php?add=add-category">Add Multilevel Category</a></li> <li><a href="user-form.php">View Multilevel Category</a></li> </ul> </div> <!--====form section start====--> <div class="right-col"> <div class="form"> <p style="color:red"><?php if(!empty($msg)){echo $msg; }?></p> <?php $add=$_GET['add']??''; switch ($add) { case 'add-category': ?> <!--==== category form=====--> <div class="form-title"> <h2>Create Nested Category</h2> </div> <form method="post" action=""> <label> category</label> <select name="parent_id"> <?php foreach ($catData as $cat) { ?> <option value="<?php echo $cat['id']; ?>"><?php echo $cat['category_name']; ?></option> <?php if( ! empty($cat['nested_categories'])){ echo display_option($cat['nested_categories'], $mark.' '); } } ?> </select> <label>Subcategory Category</label> <input type="text" placeholder="Enter Full Name" name="category_name" required> <button type="submit" name="addcat">Add Nested category</button> </form> <!--=======subcategory form====--> <?php break; default: ?> <!--=====category subcategory list=====--> <?php foreach($catData as $cat){ ?> <ul> <li> <?php echo $cat['category_name']; ?> </li> <?php if( ! empty($cat['nested_categories'])){ echo display_list($cat['nested_categories']); } ?> </ul> <!--======category subcategory list=====--> <?php } break;} ?> </div> </div> </body> </html>
Use the fol mellowing CSS code to design multilevel categories. Even you can write your own CSS code –
<style type="text/css"> .right-col table, td, th { border: 1px solid #ddd; text-align: left;} .right-col table { border-collapse: collapse; max-width: 100%; width:90%;} . right-col{ width: 75%; float: right;} .right-col th, td { padding: 15px;} .left-col form { height: 100vh; border: 2px solid #f1f1f1; padding: 16px; background-color: white;} .left-col{ width: 20%; float: left; background: #f1f1f1; height: 100vh; } .left-col a{ text-decoration: none; font-size: 20px; color: orangered; line-height: 30px} .left-col ul{ list-style-type:none;} .form input, .form select{ width: 100%; padding: 15px; margin: 5px 0 22px 0; display: inline-block; border: none; background: #f1f1f1;} .form select{ width:109%;} .form input[type=text]:focus, input[type=password]:focus { background-color: #ddd; outline: none;} .form button[type=submit] { background-color: #434140; color: #ffffff; padding: 10px 20px; margin: 8px 0; border: none; cursor: pointer; width: 111%; opacity: 0.9; font-size: 20px; } .form label{ font-size: 18px; } .form button[type=submit]:hover { background-color:#3d3c3c;} .form-title a, .form-title h2{ display: inline-block;} .form-title a{ text-decoration: none; font-size: 20px; background-color: green; color: honeydew; padding: 2px 10px;} .form{ width:30%;} </style>
My Suggestion
I have shared an example to create a Multilevel category in PHP. Now, you can easily create another large & complex multilevel category. If you have any questions, ask me through the below box.
I will share more web technology coding tutorials in the best and simple way. So, continue to visit my blog to become an expert in web coding.