How to Create Multilevel Category in PHP MySQL

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 in php

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.


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` (
  `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


$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



// 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 (?,?)");
      $exec= $query->execute();

        $msg="Category was created sucessfully";
        return $msg;
        $msg= "Error: " . $query . "<br>" . mysqli_error($conn);

function multilevel_categories($parent_id=0){

  global $conn;
  $query = $conn->prepare('SELECT * FROM categories WHERE parent_id=?');


    while($row= $exec->fetch_assoc())

   return $catData;
    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.'&nbsp;&nbsp;&nbsp;');
  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



<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<title>Multilevel Category in PHP</title>

<!--====form section start====-->
<div class="left-col">
  <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>
<!--====form section start====-->

<div class="right-col">
<div class="form">
<p style="color:red"><?php if(!empty($msg)){echo $msg; }?></p> <?php

      switch ($add) {
      case 'add-category':

       <!--==== category form=====-->
        <div class="form-title">
       <h2>Create Nested Category</h2>
       <form method="post" action="">
          <label> category</label>
          <select name="parent_id">

             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.'&nbsp;&nbsp;&nbsp;');

          <label>Subcategory Category</label>
          <input type="text" placeholder="Enter Full Name" name="category_name" required>
          <button type="submit" name="addcat">Add Nested category</button>
    <!--=======subcategory form====-->


<!--=====category subcategory list=====-->
foreach($catData as $cat){ ?>
<?php echo $cat['category_name']; ?>

      if( ! empty($cat['nested_categories'])){
        echo display_list($cat['nested_categories']);

<!--======category subcategory list=====-->




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;} 
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{
.form input, .form select{
 width: 100%; 
padding: 15px; 
margin: 5px 0 22px 0; 
display: inline-block; 
border: none; background: #f1f1f1;}
 .form select{ 
.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 { 
.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%;}


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.