How to Create Category and Subcategory in PHP

Hello Developers, I have shared the best tutorial to learn about displaying categories and subcategories on web pages. In Most projects, you need to create a Dynamic category and subcategory in PHP using MySQL. But you don’t know the simple way to implement it. So, Don’t worry, you will get the best & simple script to use in your projects.

As you know that a category is created in another category is called nested or child or subcategory. So, you need to care about its relationship. Every subcategory is always created with the id of the parent category. So, I will write the PHP MySQL Scrip with this concept.

Also Read – Multilevel Category with Tree Structure in PHP

add category and subcategory in php

Dynamic Category and Subcategory in PHP Using MySQL

You have to go through the following steps to understand and create categories and subcategories in PHP and MySQL. Therefore you must not skip any one of the given points.

1. Configure Basic Requirement

First of all, you should have to create the following folder structure for testing purposes. Otherwise, you can directly use the given script in your project.

myproject/
|__catsubcat-form.php
|__catsubcat-script.php
|__database.php
|__style.css

Create a table with the name of categories in PHPMyAdmin.

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,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Create another table with the name of subcategories  in PHPMyAdmin

Table Name – subcategories

CREATE TABLE `subcategories` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) DEFAULT 0,
  `subcategory_name` varchar(255) DEFAULT NULL,
)

Write the script to connect PHP to MYSQL Database.

File Name – database.php

 <?php

$hostname     = "localhost";
$username     = "root";
$password     = "";
$databasename = "codingstatus.com";

// Create connection
$conn = mysqli_connect($hostname, $username, $password,$databasename);
// Check connection
if (!$conn) {
    die("Unable to Connect database: " . mysqli_connect_error());
}
?>

 

2. Create a category and subcategory Form

  • Write the  HTML code to create the category form.
  • Now, Write the HTML code to create a subcategory form.
  • You have to write the HTML code to create a category and subcategory list to open those forms.

File Name – catsubcat-form.php

 <?php

include('category-script.php');
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<title>Category and SubCategory in PHP</title>
<style type="text/css">
  
.right-col{
    width: 75%;
    float: right;}

body{
    overflow-x: hidden;}
.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>
</head>
<body>
<!--====form section start====-->

<div class="left-col">
<ul>
  <li><a href="category-form.php?add=add-category">Add Category</a></li>
  <li><a href="category-form.php?add=add-subcategory">Add Subcatgory</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

 echo $add=$_GET['add']??'';
 switch ($add) {
 case 'add-category':
         
?>

<!--==== category form=====-->
<div class="form-title">
<h2>Create Category</h2>
</div>
<form method="post" action="">
   <label>Category</label>
   <input type="text" placeholder="Enter Full Name" name="category_name" required>
    <button type="submit" name="addcat">Add category</button>
</form>
<!--=======subcategory form====-->
             
<?php

     break;
     case 'add-subcategory':
         
?>

 <!--==== subcategory form=====-->
 <div class="form-title">
 <h2>Create Subcategory</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 } ?>

      </select>
    <label>Subcategory</label>
    <input type="text" placeholder="Enter Full Name" name="subcategory_name" required>
    <button type="submit" name="addsubcat">Add subcategory</button>
 </form>
 <!--=======subcategory form====-->
             
<?php

      break;
      
      default:
     
?>

<h3>Category and subcategory </h3>
             
<?php

      break;
    }
    
?>

        
    </div>
  </div>

</body>
</html>

 

3. Create Category and Subcategory in PHP

To create category and subcategory, you have to use the following functions –

  • create_category($conn) can insert category data into the database
  • create_subcategory($conn) can insert subcategory data into the database
  • fetch_categories($conn)  can fetch category data from the database
  • fetch_subcategories($conn,$parent_id) can fetch subcategory data from the database
  • legal_input($value)  can validate category and subcategory data before inserting it into the database

File Name – catsubcat-script.php

<?php

include('database.php');
if(isset($_POST['addcat'])){
   $msg=create_category($conn);     
}
if(isset($_POST['addsubcat'])){
    $msg=create_subcategory($conn);     
}

function create_category($conn){
      $category_name= legal_input($_POST['category_name']);
      $query=$conn->prepare("INSERT INTO categories (category_name) VALUES (?)");
      $query->bind_param('s',$category_name);
      $exec= $query->execute();
      if($exec){
         $msg=" Category was created successfully";
         return $msg;
      }else{
        $msg= "Error: " . $query . "<br>" . mysqli_error($conn);
      }
}


function create_subcategory($conn){
      $parent_id= legal_input($_POST['parent_id']);
      $subcategory_name= legal_input($_POST['subcategory_name']);
      $query=$conn->prepare("INSERT INTO subcategories (parent_id,subcategory_name) VALUES (?,?)");
      $query->bind_param('is',$parent_id,$subcategory_name);
      $exec= $query->execute();
      if($exec){
        $msg="Subcategory was created sucessfully";
        return $msg;
      }else{
        $msg= "Error: " . $query . "<br>" . mysqli_error($conn);
      }
}

// fetch query

$catData=fetch_categories($conn);

function fetch_categories($conn){ 
  $parent_id=0;
  $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'],
          'subcategories'=>fetch_subcategories($conn,$row['id'])
        ];  
   }
   return $catData;
        
  }else{
    return $catData=[];
  }
}

// fetch query

function fetch_subcategories($conn,$parent_id){
  $query = $conn->prepare('SELECT * FROM subcategories WHERE parent_id=?');
  $query->bind_param('i',$parent_id); 
  $query->execute();
  $exec=$query->get_result();

  $subcatData=[];
if($exec->num_rows>0){
    while($row= $exec->fetch_assoc())
    {
        $subcatData[]=[
          'id'=>$row['id'],
          'parent_id'=>$row['parent_id'],
          'subcategory_name'=>$row['subcategory_name'],
          
        ];  
   }
   return $subcatData;
        
  }else{
    return $subcatData=[];
  }
}
// convert illegal input to legal input
function legal_input($value) {
  $value = trim($value);
  $value = stripslashes($value);
  $value = htmlspecialchars($value);
  return $value;
}
?>

 

Don’t forget to include the database connection file database.php in the above file.

This PHP script can work to create any kind of category and subcategory view. You need not change anything into its script. But you can change the table name based on your project.

4. Display category and subcategory

Now, we have to display category and subcategory data in the HTML list. So you will have to follow the below points –

  • First of all, include script file category-script.php
  • Create an HTML unordered list
  • Print category and subcategory by running $catData with a foreach loop

File Name – catsubcat-list.php

 <?php

include('category-script.php');
?>

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

</head>
<body>
<!--=====category subcategory list=====-->
    
<?php

  foreach ($catData as $cat) {
      
?>

     <ul>
      <li>
          
<?php echo $cat['category_name']; ?>

              </li>
       <ul>
              
<?php
$subcatData=$cat['subcategories'];
        foreach ($subcatData as $subcat) {
            
?> <li><?php echo $subcat['subcategory_name']; ?></li> <?php

        }
      
?>

       </ul>
       </ul>
          


</body>
</html>

 

My Suggestion

I have shared an example to create a category and subcategory in PHP. Now, you can easily create more than two-level categories with the same concept. If you have any questions, ask me through the below box.

You can learn more PHP Coding in the blog. I  will share more web technology coding tutorials in the best and simple way. So, continue to visit my website.

5 thoughts on “How to Create Category and Subcategory in PHP”

Comments are closed.