PHP MySQL eCommerce Admin Panel Tutorial Tutorial

Category

In our previous article, we learned about How to create a Login Page? Now our login page is ready and employees are now able to use it for login. Now it's time to add data. For our e-commerce website and app, we need to add products. For each product, we need to assign it to a category. So first we need Categories. In this article, we are going to create a Category Page. Before starting, coding let's first understand the requirement. 

Theory or Requirement

  • Employees are able to add or edit the category.
  • Each category may have one parent and many children.
  • Each product must belong to at least one category.
  • For each category, we need to set an icon.

Following are the sample images for an app and an e-commerce website.

As per our requirement following is the database table structure for storing category.
Table Name: tblCategory
Table Columns
CategoryID: Unique ID for each Category.
CategoryName: Unique Category Name.
ParentID: ID for parent category. For first level categories, it must null.
FontID: UiRain font Icons ID.

For above table, we are referring another table tblFonts. Following is the table structure.
Table Name: tblFonts
Table Columns
FontID: Unique ID for each Font.
FontName: FontName.
FontCode: Font Code.
FontClass: Font Css Class.

Let's first create above two database table. Category table is dependent on Font table so we need to first create font table.

Database Changes

Font database table creates statement.

CREATE TABLE tblFonts
(
	FontID		BIGINT PRIMARY KEY AUTO_INCREMENT,
    FontName	 VARCHAR(200),
    FontCode	 VARCHAR(10) UNIQUE,
    FontCssClass VARCHAR(100)
)

 

Now we can create our category table.

CREATE TABLE tblCategory
(
	CategoryID				BIGINT AUTO_INCREMENT PRIMARY KEY,
    ParentID				BIGINT,
    CategoryName			VARCHAR(200) UNIQUE,
    FontID					BIGINT,
    FOREIGN KEY (ParentID) REFERENCES tblCategory(CategoryID),
    FOREIGN KEY (FontID) REFERENCES tblFonts(FontID)
);

 

Our database tables are ready. Next, we are going to create a Category Page. Let's create Category.php. Following is the code for our first category page.

<?php 
    session_start();
    $IsLogin=-1;
    if(isset($_SESSION["IsLogin"]))
    {
        $IsLogin = intval($_SESSION["IsLogin"]);
    }

    if($IsLogin<1)
    {
        header("Location: index.php");
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
      <title>Category</title>
</head>
<body>
    <form action="SaveCategory.php" method="post">
        <input type="text" id="tbCategory" name="tbCategory" placeholder="Enter a category" />
        <button type="submit">Save</button>
    </form>
</body>
</html>

 

Let's move step by step. We first created a very simple page with a form including a textbox and a submit button. When the end user enters a category and clicks on save button, our page is going to redirect on "SaveCategory.php" page.
Now create a SaveCategory.php page with following code.

<?php 
    /* Login Status Check  */
    session_start();
    $IsLogin=-1;
    if(isset($_SESSION["IsLogin"]))
    {
        $IsLogin = intval($_SESSION["IsLogin"]);
    }

    if($IsLogin<1)
    {
        header("Location: index.php");
    }
    $Result=0;


    /* Check if Form is not empty  */
    if(isset($_POST["tbCategory"]))
    {
        $Category = $_POST["tbCategory"];
        /* Some DB Constants */
        DEFINE("DB_SERVER","localhost");
        DEFINE("DB_USER","root");
        DEFINE("DB_PASSWORD","");
        DEFINE("DB_DATABASE_NAME","dealsatoxyz");

        $MySQLConnection = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE_NAME);

        // Check connection for error
        if ($MySQLConnection->connect_error) {
            die("Connection failed: " . $MySQLConnection->connect_error);
        }

        $SQLQuery = "INSERT INTO tblCategory (ParentID,CategoryName,FontID) VALUES(null,?,null);";
        // prepare and bind
        $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
        $SQLPrepare->bind_param("s", $Category);
        $SQLPrepare->execute();
        //Check affected rows and last inserted id.
        $SQLRowsAffected = $SQLPrepare->affected_rows;
        $CategoryID = $MySQLConnection->insert_id;

        if($CategoryID>0)
        {
            $Result=1;
            
        }
        else{
            $Result=-1;
            
        }
    }

    echo $Result;
    //header("Location: Category.php?S=".$Result);
?>

 

Current SaveCategory.php code save the category in database and display result for scrip execution. Following is the meaning of the result values.

  • 0 - It is the default value. If a user tries to access this page directly then the user can get the result with value equals to zero (0).
  • 1 - It means we have our form data and database insertion is successful.
  • -1 - We can get -1 when database insertion fails due to various reasons.

Let's open Category Page type "First Category" in the text box and click on Save button.
Test: We are testing our Category and SaveCategory.php code
Expected Result: 1 if "First Category" is not available in the database.
Following are the result images:

As per above images, our code is working fine. Let's refresh SaveCategory.php page. If the browser wants your confirmation select yes. We want to send the same form data one more time.

Hmmm, this time our SaveCategory.php result is -1. Why? I think you are the right person to answer this question. Please use the comment section to share your thoughts with us. Hint, please check the table structure for the category.

Now, what is next? Let's redirect the user to Category.php and display the proper error message. For this comment echo $Result; in SaveCategory.php and uncomment     following line. "header("Location: Category.php?S=".$Result);" . Save the file and one more time refresh the SaveCategory.php page. Now we are on our Category Page. This type we have error information from SaveCategory.php file. Let's display this to end user. Following are the final code for Category.php for displaying the error messages.

<?php 
    session_start();
    $IsLogin=-1;
    if(isset($_SESSION["IsLogin"]))
    {
        $IsLogin = intval($_SESSION["IsLogin"]);
    }

    if($IsLogin<1)
    {
        header("Location: index.php");
    }

    $SaveMSG="";
    if(isset($_GET["S"]))
    {
        $SaveError=intval($_GET["S"]);

        switch($SaveError)
        {
            case 1:{
                $SaveMSG="Category Saved.";
            }break;
            case 0:{
                $SaveMSG="All fields are required.";
            }break;
            case -1:{
                $SaveMSG="Category Saved Failed. Or Category already exists.";
            }break;
            
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
      <title>Category</title>
</head>
<body>
    <form action="SaveCategory.php" method="post">
        <input type="text" id="tbCategory" name="tbCategory" placeholder="Enter a category" />
        <br/>
        <span style="color:red">
            <?php echo $SaveMSG; ?>
        </span>
        <br/>
        <button type="submit">Save</button>
    </form>
</body>
</html>

 

What is next? Next, we need to add an option for selecting a parent for the new category. For this, we are going to first fetch data for existing Category from SQL database and then we are going to display it in our Category Page. Before moving ahead we have lots of duplication data for checking session status and database related configurations. Let's move all this code in a separate file. For session related code. I saved it in SessionCheck.php file. For database and website Configuration related data, we saved it in WebSiteConfig.php file. Finally, we included both the files in our Category.php file and SaveCategory.php file.
Now we need to fetch the existing Category data from the database. We are displaying existing category in a select. Following is the new changes image for our Category.php form.

<?php 
    
    require_once 'SessionCheck.php';
    require_once 'WebSiteConfig.php';
    $CategoryOptions="";
    $MySQLConnection = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE_NAME);
        // Check connection for error
    if ($MySQLConnection->connect_error) {
        die("Connection failed: " . $MySQLConnection->connect_error);
    }
    $SQLQuery = "SELECT CategoryID,CategoryName FROM tblCategory;";
    // prepare and bind
    $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
    $SQLPrepare->execute();
    $SQLResult = $SQLPrepare->get_result();
    while ($SQLRow = $SQLResult->fetch_assoc()) {
        $CategoryOptions = $CategoryOptions."<option value=\"".$SQLRow["CategoryID"]."\">".$SQLRow["CategoryName"]."</option>";
    }
    $SaveMSG="";
    if(isset($_GET["S"]))
    {
        $SaveError=intval($_GET["S"]);

        switch($SaveError)
        {
            case 1:{
                $SaveMSG="Category Saved.";
            }break;
            case 0:{
                $SaveMSG="All fields are required.";
            }break;
            case -1:{
                $SaveMSG="Category Saved Failed. Or Category already exists.";
            }break;
            
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
      <title>Category</title>
</head>
<body>
    <form action="SaveCategory.php" method="post">
        <select id="sParentID" name="sParentID">
            <option value=-1 selected>Select One</option>
            <?php echo $CategoryOptions; ?>
        </select>
        <br/>
        <input type="text" id="tbCategory" name="tbCategory" placeholder="Enter a category" />
        <br/>
        <span style="color:red">
            <?php echo $SaveMSG; ?>
        </span>
        <br/>
        <button type="submit">Save</button>
    </form>
</body>
</html>

 

Now we need to capture the parent id in SaveCategory.php and then we need to save it in the database. For this, we added following lines in our SaveCategor.php page
1. && isset($_POST["sParentID"]): Check both tgCategory and sParentID.
2. $ParentID= intval($_POST["sParentID"]);: Store ParentID in variable.
3. Database: Save it in database using following changes.
$SQLQuery = "INSERT INTO tblCategory (ParentID,CategoryName,FontID) VALUES(?,?,null);";
        // prepare and bind
        $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
        $SQLPrepare->bind_param("is", $ParentID,$Category);
        $SQLPrepare->execute();

Let's test the changes. Select "First Category" and the in the text box enter "Child Category". Finally, click on save button.

We are almost done with our category page. Now let's check how to add icons. For this, we need to first download few font files and we need to add all the required fonts data in our database. We are using UIRAIN Fonts you can download it from https://uirain.com/. Once the download is completed successfully, extract all the files and save it in your project folder. Also, add required CSS files for fonts. Following is the Insert statement for the available 13 fonts.

INSERT INTO `tblFonts`( `FontName`, `FontCode`, `FontCssClass`) VALUES 
('Fridge','e000','ur-fridge'),('Fridge Dark','e001','ur-fridge-dark')
,('Mobile','e002','ur-mobile'),('Washing Machine','e003','ur-washing-machine')
,('Electronics','e004','ur-electronics'),('TV','e005','ur-tv')
,('Laptop','e006','ur-laptop'),('Colored Fridge','f000','ur-fridge-color')
,('Colored Mobile','f001','ur-mobile-color'),('Colored Washing Machine','f002','ur-washing-machine-color')
,('Colored Electronics','f003','ur-electronics-color'),('Colored TV','f004','ur-tv-color')
,('Colored Laptop','f005','ur-electronics-color')

 

Now we are going to create another HTML select for our Fonts. First, we need to fetch the data from the database. It is similar to the category. Following is the final version (as a part of this article) for Category.php and SaveCategory.php

<?php 
    
    require_once 'SessionCheck.php';
    require_once 'WebSiteConfig.php';
    $CategoryOptions="";
    $FontOptions="";
    $MySQLConnection = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE_NAME);
        // Check connection for error
    if ($MySQLConnection->connect_error) {
        die("Connection failed: " . $MySQLConnection->connect_error);
    }
    $SQLQuery = "SELECT CategoryID,CategoryName FROM tblCategory;";
    // prepare and bind
    $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
    $SQLPrepare->execute();
    $SQLResult = $SQLPrepare->get_result();
    while ($SQLRow = $SQLResult->fetch_assoc()) {
        $CategoryOptions = $CategoryOptions."<option value=\"".$SQLRow["CategoryID"]."\">".$SQLRow["CategoryName"]."</option>";
    }

    $SQLQuery = "SELECT `FontID`, `FontName`, `FontCssClass` FROM `tblFonts`;";
    // prepare and bind
    $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
    $SQLPrepare->execute();
    $SQLResult = $SQLPrepare->get_result();
    while ($SQLRow = $SQLResult->fetch_assoc()) {
        echo
        $FontOptions = $FontOptions."<option value=\"".$SQLRow["FontID"]."\">".$SQLRow["FontName"]."</option>";
    }

    $SaveMSG="";
    if(isset($_GET["S"]))
    {
        $SaveError=intval($_GET["S"]);

        switch($SaveError)
        {
            case 1:{
                $SaveMSG="Category Saved.";
            }break;
            case 0:{
                $SaveMSG="All fields are required.";
            }break;
            case -1:{
                $SaveMSG="Category Saved Failed. Or Category already exists.";
            }break;
            
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
      <title>Category</title>
      <link href="font-ui-rain.css" rel="stylesheet">
</head>
<body>
    <form action="SaveCategory.php" method="post">
        <select id="sParentID" name="sParentID">
            <option value=-1 selected>Select One</option>
            <?php echo $CategoryOptions; ?>
        </select>

        <select id="sFontID" name="sFontID">
            <?php echo $FontOptions; ?>
        </select>

        <br/>
        <input type="text" id="tbCategory" name="tbCategory" placeholder="Enter a category" />
        <br/>
        <span style="color:red">
            <?php echo $SaveMSG; ?>
        </span>
        <br/>
        <button type="submit">Save</button>
    </form>
</body>
</html>

 

<?php 
    /* Login Status Check  */
    
    require_once 'SessionCheck.php';
    require_once 'WebSiteConfig.php';
    $Result=0;

    /* Check if Form is not empty  */
    if(
        isset($_POST["tbCategory"])
        && isset($_POST["sParentID"])
        && isset($_POST["sFontID"])
    )
    {
        $Category = $_POST["tbCategory"];
        $ParentID= intval($_POST["sParentID"]);
        $FontID = intval($_POST["sFontID"]);
        $MySQLConnection = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE_NAME);

        // Check connection for error
        if ($MySQLConnection->connect_error) {
            die("Connection failed: " . $MySQLConnection->connect_error);
        }

        $SQLQuery = "INSERT INTO tblCategory (ParentID,CategoryName,FontID) VALUES(?,?,?);";
        // prepare and bind
        $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
        $SQLPrepare->bind_param("isi", $ParentID,$Category,$FontID);
        $SQLPrepare->execute();
        //Check affected rows and last inserted id.
        $SQLRowsAffected = $SQLPrepare->affected_rows;
        $CategoryID = $MySQLConnection->insert_id;

        if($CategoryID>0)
        {
            $Result=1;
            
        }
        else{
            $Result=-1;
            
        }
    }
    //echo $Result;
    header("Location: Category.php?S=".$Result);
?>

 

Let's test the changes and add few categories. We are going to add following categories

  • Electronics
    • Fridge
    • Mobile and Tablets
    • Laptop
    • Washing Machine

Following image show the final data we have in our Category Database table.

<?php 
    /* Login Status Check  */
    
    require_once 'SessionCheck.php';
    require_once 'WebSiteConfig.php';
    $Result=0;

    /* Check if Form is not empty  */
    if(
        isset($_POST["tbCategory"])
        && isset($_POST["sParentID"])
        && isset($_POST["sFontID"])
    )
    {
        $Category = $_POST["tbCategory"];
        $ParentID= intval($_POST["sParentID"]);
        $FontID = intval($_POST["sFontID"]);
        $MySQLConnection = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE_NAME);

        // Check connection for error
        if ($MySQLConnection->connect_error) {
            die("Connection failed: " . $MySQLConnection->connect_error);
        }

        $SQLPrepare=null;
        if($ParentID==-1)
        {
            $SQLQuery = "INSERT INTO tblCategory (ParentID,CategoryName,FontID) VALUES(null,?,?);";
            // prepare and bind
            $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
            $SQLPrepare->bind_param("si",$Category,$FontID);
        }
        else{
            $SQLQuery = "INSERT INTO tblCategory (ParentID,CategoryName,FontID) VALUES(?,?,?);";
            // prepare and bind
            $SQLPrepare = $MySQLConnection->prepare($SQLQuery);
            $SQLPrepare->bind_param("isi", $ParentID,$Category,$FontID);
        }

        
        $SQLPrepare->execute();
        //Check affected rows and last inserted id.
        $SQLRowsAffected = $SQLPrepare->affected_rows;
        $CategoryID = $MySQLConnection->insert_id;

        if($CategoryID>0)
        {
            $Result=1;
            
        }
        else{
            $Result=-1;
            
        }
    }
    //echo $Result;
    header("Location: Category.php?S=".$Result);
?>

 

Before moving to the next article we need to integrate our code with Gentelella admin theme. For this, we are going to use plain_page.html file code. We are going to use this page as a starting point for our next articles. So for this let's break the code for the plain_page.html file into multiple files. As per following images, we are going to break our plain_page.html code into 5 different sections.

  1. HTMLHeader.php : Store Include and Other MetaData Informations.
  2. LeftMenu.php: No 1 in the image. Left Side Menu HTML Code.
  3. TopNavigation.php: No 2 in the image. Theme Body Head Code.
  4. Body Content: No 3 in the image. Actual Body Content. It is going to be inside the actual new file.
  5. BodyFooter.php: It stores Body Footer Code
  6. HTMLFooter.php: Script Files. So we can add a new script it will reflect everywhere.

Let's break our plain_page.html file and create a PlainPage.php file using the same logic. You can find the code for the PlainPage.php file in the source code for this article. Following are the reference images.

In our LeftMenu.php we have lots of items. Let's remove the unwanted Menu and Items. Finally, add Dashboard and Category under Home.

Now, whenever we need to create a new page we are going to create a copy of PlainPage.php include the required file, and then in the Body Content Section, we are going to use our actual page content.
Using the same logic when we are going to modify Category.php then we are going to include

  • SessionCheck.php
  • WebSiteConfig.php
  • Existing PHP Code on Top
  • HTMLHeader.php
  • LeftMenu.php
  • TopNavigation.php
  • Body Content: We need to use our form which we created in the previous version of Category.php.
  • BodyFooter.php
  • HTMLFooter.php

In the last, we are going to modify our form elements based on the form.html available in the production folder. Refer the following image for the updated Category.php file.

Following is the download link for the final version of the source code for this article.

FileTypeSizeDownload
Category - PHP MySQL eCommerce Admin Panel Tutorial.zipNA19692Login to Download
...

About The Author

Hello, I am Mayank Sanghvi I am primarily a BI developer with experience in MSBI and Cognos BI Suit. Also having interest in various other technologies such as Android, Java, C#, ASP .NET and other. I enjoy learning new technologies and share my experience with others.

0 Comments
Leave A Comment

Please login to post your valuable comments.

add