Dj Techblog

A blog on web development

Admin panel with Category Subcategory setup for ecommerce website in php

Last modified on June 03, 2022
Register user with admin approval in php

Ecommerce website with different products and itmes need to be categorized into categories and subcategories. In this article I will show how you can build a fully functional admin panel that creates, display, edit and delete category subcategory tree dynamically for an ecommerce shopping website. The web technologies I have used here is simple html, bootstrap, php, ajax and jquery.

Every category will have a list of subcategories which makes it a tree like structure. We can add as many as subcategory under a category and browse them. With each category and sub category there will be a delete button to delete it. Deleteing a category will delete all the subcategories under it, you can also delete a particular subcategory. While adding a product choosing a category will display a list of subcategories under it in a dropdown menu. This kind of category and subcategories setup in admin panel makes an ecommerce website management easier.

We will follow these basic steps to complete this project:

  1. Create two tables category and subcategory.
  2. Two forms to create category and subcategory dynamically.
  3. Display categories and subcategories in a tree like structure.
  4. Delete option to delete any category or subcategory.

Recommended read,

Regsiter user with admin approval in php

Admin panel to add update delete products for ecommerce webiste in php

Add a shopping cart to ecommerce website in php

Create two tables category and subcategory

The category table will have only two columns id and name. Add a primary key id and the name column unique, that is do not allow any duplicate category name in the table.

    CREATE TABLE category (id INT NOT NULL , name TEXT NOT NULL );
    ALTER TABLE category ADD PRIMARY KEY (id);
    ALTER TABLE category ADD UNIQUE (name);

The subcategory table will have three columns id, sid and name. Add a primary key sid, foreign key sid which points to id in the parent table category. The foreign key constraint ensures that there can never exist a subcategory without a category and once a category is deleted all the subcategories under it will also be deleted. Also make the name column unique, that is do not allow any duplicate sub-category name in the table.

    CREATE TABLE subcategory ( id INT NOT NULL , sid INT NOT NULL , name TEXT NOT NULL );
    ALTER TABLE subcategory ADD PRIMARY KEY (sid);
    ALTER TABLE subcategory ADD FOREIGN KEY (id) REFERENCES category (id);
    ALTER TABLE subcategory ADD UNIQUE (name);

add-categories.php: Two forms to create category and subcategory dynamically.

Design two forms one for category and another for subcategory. The form will take values from admin and pass it to server via ajax call. The submit button in the form will call a javascript function addcategory(). The function will receive the input and pass it to php server via ajax call. The php server later inserts the value to the table in mysql server.

This is an admin panel which can only be accessed by admin. You need to use php sessions to check for admin.

<?
        $db = mysqli_connect('server-name', 'username', 'password', 'database-name');
        $query = "SELECT * FROM category";
        $result = mysqli_query($db, $query);
        if(!$result){
             die(mysqli_error());
             exit();
        }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Categories</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <style>
        .text-font{
            font-size: 35px;
            font-weight: bolder;
        }
        .height{
            height: 100vh   ;
        }
        .error{
                color: red;
                font-size: large;
            
            }
            .success{
                color: green;
                font-size: large;
          
            }
            .error1{
                color: red;
                font-size: large;
            
            }
            .success1{
                color: green;
                font-size: large;
          
            }
            .error2{
                color: red;
                font-size: large;
            
            }
            .success2{
                color: green;
                font-size: large;
          
            }
    </style>
       
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-2 bg-dark height">
                <p class="pt-5 pb-5 text-center">
                    <a href="admin-panel.php" class="text-decoration-none"><span class="text-light text-font">Admin</span></a>
                </p>
                <hr class="bg-light ">
                 <p class="pt-2 pb-2 text-center">
                    <a href="admin-profile.php" class="text-decoration-none"><span class="text-light">Profile</span></a>
                </p>
                <hr class="bg-light ">
                 <p class="pt-2 pb-2 text-center">
                    <a href="add-categories.php" class="text-decoration-none"><span class="text-light">Add Categories</span></a>
                </p>
                <hr class="bg-light ">
                 <p class="pt-2 pb-2 text-center">
                    <a href="display-categories.php" class="text-decoration-none"><span class="text-light">Display Categories</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="products-add.php" class="text-decoration-none"><span class="text-light">Add Products</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="products-display.php" class="text-decoration-none"><span class="text-light">View Products</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="new-user-requests.php" class="text-decoration-none"><span class="text-light">New user requests</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="view-users.php" class="text-decoration-none"><span class="text-light">View user</span></a>
                </p>                
                <hr class="bg-light ">
            </div>
            <div class="col-sm-10 bg-light">
               <div class="row">
                   <div class="col-sm-2">
                       <p class="text-center pt-5">
                                    <img class="rounded" src="<?php echo ("/test123/profile-pic/") . ($_SESSION['email']) . "display-picture.jpg"; ?>" width="150px" height="140px">
                                </p>
                   </div>
                   <div class="col-sm-8">
                       <h1 class="text-center pt-4 pb-5"><strong>Categories</strong>
                       <hr class="w-25 mx-auto">
                   </div>
                   <div class="col-sm-2">
                       <p class="pt-5 text-center">
                            <a href="logout.php" class="btn btn-outline-primary">Logout</a>
                       </p>
                   </div>
               </div>
                <div class="row ">
                    <div class="col-sm-10">
                        <p class="text-center">
                            <strong>Add categories</strong>
                        </p>
                        <form class="form-control mx-auto w-50" action="" method="post">
                            <label class="pt-2 pb-4 text-center">Enter a category</label>
                            <input class="form-control" type="text" id="category" placeholder="Enter a category">
                            <br>
                            <input type="button" class="form-control  btn btn-primary" onclick="addcategory()" value="Add a category">
                            <div class="error pt-2"></div><div class="pt-2 success"></div>
                        </form>
                        <p class="text-center pt-3">
                            <strong>Add Sub-categories</strong>
                        </p>
                        <form class="form-control mx-auto w-50" action="" method="post">
                            <label class="pt-2 pb-4 text-center" for="categories">Choose a category</label>
                            <select class="form-control" id="categories" name="categories">
                                <option value="">------</option>
                            <?php while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ ?>
                                     <option value="<?php echo $row['id'];?>"><?php echo ($row['name']); ?></option>
                             <?php } ?>
                             </select>
                             <br>
                            <label class="pt-1 pb-4 text-center">Enter a sub category</label>
                            <input class="form-control" type="text" id="subcategory" placeholder="Enter a sub category">
                            <br>
                            <input type="button" class="form-control btn btn-primary" onclick="addsubcategory()" value="Add a Sub category">
                            <div class="error1 pt-2"></div><div class="success1 pt-2"></div>
                        </form>
                    </div>
                    
                    <div class="error2"></div><div class="success2"></div>
                    <script>
                        
                        function addcategory(){
                            var x = $('#category').val();
                            var input = {
                                "category" : x,
                                "action" : 'addcategory'
                            };
                            $.ajax({
                                url : 'controller.php',
                                type : 'POST',
                                dataType : "json",
                                data : input,
                                success : function(response)
                                {
                                    $('.success').html(response.message).show();
                                    $('.error').hide();
                                },
                                error : function(response)
                                {
                                     $('.error').html("Sub category already exist.").show();
                                     $('.success').hide();
                                }
                            });
                            
                        }
                        function addsubcategory(){
                            var x = $('#subcategory').val();
                            var id = $('#categories').val();
                            var input = {
                                "subcategory" : x,
                                "id" : id,
                                "action" : 'addsubcategory'
                            };
                            $.ajax({
                                url : 'controller.php',
                                type : 'POST',
                                dataType : "json",
                                data : input,
                                success : function(response)
                                {
                                    $('.success1').html(response.message).show();
                                    $('.error1').hide();
                                },
                                error : function(response)
                                {
                                     $('.error1').html("Sub category already exist.").show();
                                     $('.success1').hide();
                                }
                            });
                            
                        }
                    </script>
                </div>
            </div>
        </div>
    </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>
                    

display-categories.php: Display all the categories and subcategories.

The admin panel must have functionality to browse all the categories and subcategories dynamically. The categories and subcategories must have delete option so that one can delete them when needed. The delete is a cascaded delete, that is once a category is deleted, all the associated subcategories will be deleted automatically. So, that there is no anomaly in the database.

The del-category.php and del-subcategory.php page will delete the category and subcategories respectively.

<?
        $db = mysqli_connect('server-name', 'user-name', 'password', 'database-name');
        $query = "SELECT * FROM category";
        $result = mysqli_query($db, $query);
        if(!$result){
             die(mysqli_error());
             exit();
        }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Browse Categories</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <style>
        .text-font{
            font-size: 35px;
            font-weight: bolder;
        }
        .height{
            height: 100vh   ;
        }
        .error{
                color: red;
                font-size: large;
            
            }
            .success{
                color: green;
                font-size: large;
          
            }
            .error1{
                color: red;
                font-size: large;
            
            }
            .success1{
                color: green;
                font-size: large;
          
            }
            .error2{
                color: red;
                font-size: large;
            
            }
            .success2{
                color: green;
                font-size: large;
          
            }
    </style>
       
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-2 bg-dark height">
                <p class="pt-5 pb-5 text-center">
                    <a href="admin-panel.php" class="text-decoration-none"><span class="text-light text-font">Admin</span></a>
                </p>
                <hr class="bg-light ">
                 <p class="pt-2 pb-2 text-center">
                    <a href="admin-profile.php" class="text-decoration-none"><span class="text-light">Profile</span></a>
                </p>
                <hr class="bg-light ">
                 <p class="pt-2 pb-2 text-center">
                    <a href="add-categories.php" class="text-decoration-none"><span class="text-light">Add Categories</span></a>
                </p>
                <hr class="bg-light ">
                 <p class="pt-2 pb-2 text-center">
                    <a href="display-categories.php" class="text-decoration-none"><span class="text-light">Display Categories</span></a>
                </p>
                
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="products-add.php" class="text-decoration-none"><span class="text-light">Add Products</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="products-display.php" class="text-decoration-none"><span class="text-light">View Products</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="new-user-requests.php" class="text-decoration-none"><span class="text-light">New user requests</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="view-users.php" class="text-decoration-none"><span class="text-light">View user</span></a>
                </p>                
                <hr class="bg-light ">
                
                
                
            </div>
            <div class="col-sm-10 bg-light">
               <div class="row">
                   <div class="col-sm-2">
                       <p class="text-center pt-5">
                                    <img class="rounded" src="<?php echo ("/test123/profile-pic/") . ($_SESSION['email']) . "display-picture.jpg"; ?>" width="150px" height="140px">
                                </p>
                   </div>
                   <div class="col-sm-8">
                       <h1 class="text-center pt-4 pb-5"><strong>Browse Categories/Subcategories</strong>
                       <hr class="w-25 mx-auto">
                   </div>
                   <div class="col-sm-2">
                       <p class="pt-5 text-center">
                            <a href="logout.php" class="btn btn-outline-primary">Logout</a>
                       </p>
                   </div>
               </div>
                <div class="row ">
                    
                    <div class="col-sm-10 w-50 mx-auto rounded bg-white">
                        <h3 class="text-center pt-2 pb-5">
                            <strong>Delete/Edit Categories</strong>
                        </h3>
                        <ol>
                            <?php 
                                    $db = mysqli_connect('server-name', 'user-name', 'password', 'database-name');
                                    $query = "SELECT * FROM category";
                                    $result = mysqli_query($db, $query);
                                    if(!$result){
                                         die(mysqli_error());
                                         exit();
                                    }
                                    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ ?>
                                        <li>
                                            
                                            <form action="del-category.php" method="post">
                                                <?php echo ($row['name']); ?> 
                                            <input type="hidden" name="category-name" value="<?php echo ($row['name']); ?> ">
                                            <button type="submit" class="btn btn-link text-decoration-none">Delete</button>
                                            </form>
                                            <ol>
                                                <?php 
                                                        $db1 = mysqli_connect('server-name', 'user-name', 'password', 'database-name');
                                                        $ID = $row['id'];
                                                        $query1 = "SELECT * FROM subcategory WHERE id='$ID' ";
                                                        $result1 = mysqli_query($db1, $query1);
                                                        if(!$result1){
                                                             die(mysqli_error());
                                                             exit();
                                                        }
                                                        while($row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)){ ?>
                                                            <li>
                                                                <form action="del-subcategory.php" method="post">
                                                                    <?php echo ($row1['name']); ?> 
                                                                    <input type="hidden" name="subcategory-id" value="<?php echo ($row1['sid']); ?> ">
                                                                    <button type="submit" class="btn btn-link text-decoration-none">Delete</button>
                                                                </form>
                                                            </li>
                                                <?php } ?>
                                            </ol>
                                        </li>
                            <?php } ?>
                        </ol>
                    </div>
                    <div class="error2"></div><div class="success2"></div>
                    <script>
                        
                        function addcategory(){
                            var x = $('#category').val();
                            var input = {
                                "category" : x,
                                "action" : 'addcategory'
                            };
                            $.ajax({
                                url : 'controller.php',
                                type : 'POST',
                                dataType : "json",
                                data : input,
                                success : function(response)
                                {
                                    $('.success').html(response.message).show();
                                    $('.error').hide();
                                },
                                error : function(response)
                                {
                                     $('.error').html("Sub category already exist.").show();
                                     $('.success').hide();
                                }
                            });
                            
                        }
                        function addsubcategory(){
                            var x = $('#subcategory').val();
                            var id = $('#categories').val();
                            var input = {
                                "subcategory" : x,
                                "id" : id,
                                "action" : 'addsubcategory'
                            };
                            $.ajax({
                                url : 'controller.php',
                                type : 'POST',
                                dataType : "json",
                                data : input,
                                success : function(response)
                                {
                                    $('.success1').html(response.message).show();
                                    $('.error1').hide();
                                },
                                error : function(response)
                                {
                                     $('.error1').html("Sub category already exist.").show();
                                     $('.success1').hide();
                                }
                            });
                            
                        }
                    </script>
                </div>
            </div>
        </div>
    </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>
                    

del-category.php: Delete a category

The view page contains a Delete Category button, clicking the button will delete the category.

<?php
        $category = $_POST['category-name'];
        $db = mysqli_connect('server-name', 'user-name', 'password', 'database-name');
        $query = "DELETE FROM category where name = '$category'";
        $result = mysqli_query($db, $query);
        if ($result == FALSE) 
        {
            die(mysqli_error());
            echo "Error";
            exit();
        }
        else{
            echo "Category deleted";
            $URL="categories.php";
            echo "<?script type='text/javascript'>document.location.href='{$URL}';<?/script?>";
            echo '<?META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '"?>';
        }
?>
                            

del-subcategory.php: Delete a subcategory

The view page contains a Delete Subcategory button, clicking the button will delete the subcategory.

<?php                   
    $sid = $_POST['subcategory-id'];
    $db = mysqli_connect('server-name', 'user-name', 'password', 'database-name');
    $query = "DELETE FROM subcategory where sid = '$sid'";
    $result = mysqli_query($db, $query);
    if ($result == FALSE) 
    {
        die(mysqli_error());
        echo "Errorbb";
        exit();
    }
    else{
        
        echo "Subcategory deleted";
        $URL="categories.php";
        echo "<script type='text/javascript'>document.location.href='{$URL}';</script>";
        echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">';
    }
?>

Published on July 7, 2021


Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.