Creating a Custom Inventory Management Application in PHP and MySQL

Introduction

You do not need bloated enterprise software to effectively track your inventory. This tutorial will help you develop your own custom inventory tracking system so you can make smart inventory decisions based on timely and accurate inventory data.

System Requirements

Our Inventory System requires the standard commercial phpGrid and phpChart license as it needs a few advanced features from both components.

  • PHP 7+
  • MySQL or MariaDB
  • phpGrid
  • phpChart (for reports)

What is in an Inventory Management System

An inventory management system has several critical components. At its core, inventory control works by tracking the two main functions of a warehouse — receiving (incoming) and shipping (outgoing). Other activities such as movement, or relocating, of inventory also take place. Raw materials are decremented and finished goods are incremented.

  • Incoming shipments
  • Outgoing orders
  • Inventory
  • Suppliers

Inventory System Database Diagram

Typically, an inventory system has four basic elements – products, purchases, orders, and suppliers – which must be tracked based on their location, SKU, and quantity. Current inventory, or products on hand, is updated by tracking incoming shipments and outgoing orders. Order alerts can be set to trigger when inventory levels fall below custom-defined minimum levels.

Inventory Manager DB Schema

Setting up the Inventory Manager Database

Get the InventoryManager.sql SQL script in the end of this tutorial, and then execute the script using a MySQL tool such as MySQL Workbench. This will create a new database named InventoryManager as well as the tables needed for this tutorial.

Set up phpGrid

We will use phpGrid as our datagrid component to handle all internal database CRUD (Create, Remove, Update, and Delete) operations.

Be sure to download a copy of phpGrid before you proceed.

To install phpGrid, follow these steps:

  1. Unzip the phpGrid download file.
  2. Upload the phpGrid folder to the phpGrid folder.
  3. Complete the installation by configuring the conf.php file.

Before we begin coding, we must include the following information in conf.php, the phpGrid configuration file.

1
2
3
4
5
6
define('PHPGRID_DB_HOSTNAME', 'localhost'); //  host name
define('PHPGRID_DB_USERNAME', 'root'); // database user name
define('PHPGRID_DB_PASSWORD', ''); // database password
define('PHPGRID_DB_NAME', 'InventoryManager'); // our donation manager database name
define('PHPGRID_DB_TYPE', 'mysql'); // database type
define('PHPGRID_DB_CHARSET','utf8'); // always 'utf8' in MySQL

Creating the User Interface (UI)

The application has four pages:

  • Current Inventory
  • Incoming Purchases
  • Orders to Ship
  • Reports

Inventory UI

The include file for the menu is stored in an inc folder named menu.php. The code for the menu is straightforward. For the sake of focus, we will not go into great detail. Feel free to look at the code inside the inc folder.

We have also added a menu item named Reports.

Menu

Pages

We will use the same page template we used for the CRM and Project Management tutorials.

Current Inventory

Let’s start with the Current Inventory page.

Incoming purchases increase the inventory while outgoing orders decrease it. From a master-detail perspective, the Current Inventory has not one, but two detail datagrids – the Purchases (incoming purchases) and the Orders (outgoing orders).

Therefore, the Current Inventory page is composed of one master grid – the Current Inventory in stock – and two detail grids – Incoming Purchases and Outgoing Orders. We can easily present these relationships using the phpGrid one master and multiple detail datagrids feature.

If you have read the last tutorial Building a Donation Manager from Scratch, you will have no problem following the code below.

Note the use of the set_col_format() function used to format the integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$dgProd = new C_DataGrid('SELECT * FROM products', 'id', 'products');
$dgProd->set_col_hidden('id', false);
$dgProd->enable_autowidth(true)->set_dimension('auto', '200px')->set_pagesize(100);

$dgProd->set_col_title('ProductName', 'Name');
$dgProd->set_col_title('PartNumber', 'Part Number');
$dgProd->set_col_title('ProductLabel', 'Label');
$dgProd->set_col_title('StartingInventory', 'Starting Inventory');
$dgProd->set_col_title('InventoryReceived', 'Inventory Received');
$dgProd->set_col_title('InventoryShipped', 'Inventory Shipped');
$dgProd->set_col_title('InventoryOnHand', 'Inventory On Hand');
$dgProd->set_col_title('MinimumRequired', 'Minimum Required');

$dgProd->set_col_format('StartingInventory', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('InventoryReceived', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('InventoryShipped', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('InventoryOnHand', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('MinimumRequired', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->enable_edit('FORM');

That’s it for the Current Inventory datagrid. Here’s what it looks like so far:

products

Now, let’s make a few changes to enhance our Product datagrid.

First of all, we will add some conditional formatting so that whenever the InventoryOnHand is set to zero or a negative value, it is displayed using a different background color. We will use the set_conditional_format() function for this purpose.

1
2
3
4
5
 $dgProd->set_conditional_format(
    'InventoryOnHand', 'CELL',
        array("condition"=>"lt",
          "value"=>"1",
          "css"=> array("color"=>"red","background-color"=>"#DCDCDC")));

The above code adds a display condition so that whenever the InventoryOnHand field has a value that is less than (lt) one, the text color changes to red and the background color to dark gray (#DCDCDC).

Secondly, whenever the InventoryOnHand is less than the value shown in MinimumRequired, we would like to alert the user by displaying it in a prominent background color such as gold. To compare values between two fields, we must switch to Javascript because the set_conditional_format() function only works with a single field.

The code below uses a for loop to iterate through each row in the Products datagrid. It compares the inventoryOnHand with theminimumRequired and, when condition is met, it will use thesetCell function to change the background color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 $onGridLoadComplete = <<<ONGRIDLOADCOMPLETE
function(status, rowid)
{
    var ids = jQuery("#products").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++)
    {
        var rowId = ids[i];
        var rowData = jQuery('#products').jqGrid ('getRowData', rowId);

        var inventoryOnHand = $("#products").jqGrid("getCell", rowId, "InventoryOnHand");
        var minimumRequired = $("#products").jqGrid("getCell", rowId, "MinimumRequired");

        // compare two dates and set custom display in another field "status"
        console.log(inventoryOnHand + " | " + minimumRequired);
        if(parseInt(inventoryOnHand) < parseInt(minimumRequired)){

            $("#products").jqGrid("setCell", rowId, "PartNumber", '', {'background-color':'gold'});

        }
    }

}
ONGRIDLOADCOMPLETE
;
$dgProd->add_event("jqGridLoadComplete", $onGridLoadComplete);

You can learn more about comparing multiple cell values on the phpGrid support website,

Next, on the same page, we need to see the purchases coming in (Incoming) and orders going out (Outgoing) for a specific product.

Purchases Detail Grid (Incoming)

1
2
3
4
5
6
 // Purchases detail grid
$dgPur = new C_DataGrid('SELECT id, PurchaseDate, ProductId, NumberReceived, SupplierId FROM purchases', 'id', 'purchases');
$dgPur->set_col_hidden('id', false)->set_caption('Incoming Purchases');
$dgPur->set_col_edittype('ProductId', 'select', "select id, ProductLabel from products");
$dgPur->set_col_edittype('SupplierId', 'select', "select id, supplier from suppliers");
$dgPur->set_dimension('800px');

Orders Detail Grid (Outgoing)

1
2
3
4
5
6
 // Orders detail grid
$dgOrd = new C_DataGrid('SELECT id, OrderDate, ProductId, NumberShipped, First, Last FROM orders', 'id', 'orders');
$dgOrd->set_sortname('OrderDate', 'DESC')->set_caption('Outgoing Orders');
$dgOrd->set_col_hidden('id', false);
$dgOrd->set_col_edittype('ProductId', 'select', "select id, ProductLabel from products");
$dgOrd->set_dimension('800px');

Both detail grids use the same foreign key ProductId to link to the master datagrid – Products.

1
2
 $dgProd->set_masterdetail($dgPur, 'ProductId', 'id');
$dgProd->set_masterdetail($dgOrd, 'ProductId', 'id');

Finally, our complete code to manage the Current Inventory page is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 $dgProd = new C_DataGrid('SELECT * FROM products', 'id', 'products');
$dgProd->set_col_hidden('id', false);
$dgProd->enable_autowidth(true)->set_dimension('auto', '200px')->set_pagesize(100);

$dgProd->set_col_title('ProductName', 'Name');
$dgProd->set_col_title('PartNumber', 'Part Number');
$dgProd->set_col_title('ProductLabel', 'Label');
$dgProd->set_col_title('StartingInventory', 'Starting Inventory');
$dgProd->set_col_title('InventoryReceived', 'Inventory Received');
$dgProd->set_col_title('InventoryShipped', 'Inventory Shipped');
$dgProd->set_col_title('InventoryOnHand', 'Inventory On Hand');
$dgProd->set_col_title('MinimumRequired', 'Minimum Required');

$dgProd->set_col_format('StartingInventory', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('InventoryReceived', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('InventoryShipped', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('InventoryOnHand', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));
$dgProd->set_col_format('MinimumRequired', 'integer', array('thousandsSeparator'=>',', 'defaultValue'=>'0'));

$dgProd->set_conditional_format('InventoryOnHand', 'CELL', array("condition"=>"lt",
                                                  "value"=>"1",
                                                  "css"=> array("color"=>"red","background-color"=>"#DCDCDC")));

$onGridLoadComplete = <<<ONGRIDLOADCOMPLETE
function(status, rowid)
{
    var ids = jQuery("#products").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++)
    {
        var rowId = ids[i];
        var rowData = jQuery('#products').jqGrid ('getRowData', rowId);

        var inventoryOnHand = $("#products").jqGrid("getCell", rowId, "InventoryOnHand");
        var minimumRequired = $("#products").jqGrid("getCell", rowId, "MinimumRequired");

        // compare two dates and set custom display in another field "status"
        console.log(inventoryOnHand + " | " + minimumRequired);
        if(parseInt(inventoryOnHand) < parseInt(minimumRequired)){

            $("#products").jqGrid("setCell", rowId, "PartNumber", '', {'background-color':'gold'});

        }
    }

}
ONGRIDLOADCOMPLETE
;

$dgProd->add_event("jqGridLoadComplete", $onGridLoadComplete);
$dgProd->enable_edit('FORM');

// Purchases detail grid
$dgPur = new C_DataGrid('SELECT id, PurchaseDate, ProductId, NumberReceived, SupplierId FROM purchases', 'id', 'purchases');
$dgPur->set_col_hidden('id', false)->set_caption('Incoming Purchases');
$dgPur->set_col_edittype('ProductId', 'select', "select id, ProductLabel from products");
$dgPur->set_col_edittype('SupplierId', 'select', "select id, supplier from suppliers");
$dgPur->set_dimension('800px');

// Orders detail grid
$dgOrd = new C_DataGrid('SELECT id, OrderDate, ProductId, NumberShipped, First, Last FROM orders', 'id', 'orders');
$dgOrd->set_sortname('OrderDate', 'DESC')->set_caption('Outgoing Orders');
$dgOrd->set_col_hidden('id', false);
$dgOrd->set_col_edittype('ProductId', 'select', "select id, ProductLabel from products");
$dgOrd->set_dimension('800px');

$dgProd->set_masterdetail($dgPur, 'ProductId', 'id');
$dgProd->set_masterdetail($dgOrd, 'ProductId', 'id');
$dgProd->display();

Here’s the a snapshot of the inventory page:

Current inventory

Incoming Purchases

The next page is the Incoming Purchase page. It is similar to the Purchase Detail Grid we saw when setting up the Current Inventory page. We group the purchases by ProductId and display the sum inNumberReceived. Any incoming purchases will increase the inventory.

1
2
 $dgPur -> set_group_properties('ProductId', false, true, true, false);
$dgPur -> set_group_summary('NumberReceived','sum');

The complete code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 $dgPur = new C_DataGrid('SELECT id, PurchaseDate, ProductId, NumberReceived, SupplierId FROM purchases', 'id', 'purchases');
$dgPur->set_col_hidden('id', false);

$dgPur->set_col_title('PurchaseDate', 'Date of Purchase');
$dgPur->set_col_title('ProductId', 'Product');
$dgPur->set_col_title('NumberReceived', 'Number Received');
$dgPur->set_col_title('SupplierId', 'Supplier');

$dgPur->set_col_edittype('ProductId', 'select', "select id, ProductLabel from products");
$dgPur->set_col_edittype('SupplierId', 'select', "select id, supplier from suppliers");

// $dgPur->enable_edit('FORM');
$dgPur->set_pagesize(100);

$dgPur->set_col_width('PurchaseDate', '50px');
$dgPur->set_col_width('NumberReceived', '35px');

$dgPur -> set_group_properties('ProductId', false, true, true, false);
$dgPur -> set_group_summary('NumberReceived','sum');

$dgPur->enable_autowidth(true);
$dgPur->display();

Here’s a screenshot of our Incoming Purchases page with grouping enabled:

Incoming purchases

Outgoing Orders

The next page is the Outgoing Orders page. It is similar to the Orders Detail Grid from the Current Inventory page. Here, we will introduce an advanced function called set_grid_method().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 $dgOrd = new C_DataGrid('SELECT id, OrderDate, ProductId, NumberShipped, First, Last FROM orders', 'id', 'orders');
$dgOrd->set_sortname('OrderDate', 'DESC');
$dgOrd->set_col_hidden('id', false);

$dgOrd->set_col_title('OrderDate', 'Order Date');
$dgOrd->set_col_title('ProductId', 'Product');
$dgOrd->set_col_title('NumberShipped', 'Number Shipped');

$dgOrd->set_col_edittype('ProductId', 'select', "select id, ProductLabel from products");

// $dgOrd->enable_edit('FORM');
$dgOrd->set_pagesize(100);

$dgOrd->set_col_width('OrderDate', '30px');
$dgOrd->set_col_width('NumberShipped', '35px');
$dgOrd->set_col_width('First', '20px');
$dgOrd->set_col_width('Last', '20px');

$dgOrd->set_grid_method('setGroupHeaders', array(
                                array('useColSpanStyle'=>true),
                                'groupHeaders'=>array(
                                        array('startColumnName'=>'First',
                                              'numberOfColumns'=>2,
                                              'titleText'=>'Customer Name') )));

$dgOrd->enable_autowidth(true);
$dgOrd->display();

Summary

This tutorial builds a simple and extendable inventory system in less than 50 lines of code. The progressive style of these tutorials also helps the reader to ultimately become more familar and comfortable with phpGrid by introducing a limited number of new phpGrid features in each one.

What’s Coming Up

This marks the end of the code needed to create the datagrids required for this tutorial. However, we are not done yet. There is still one more page we need to create — Reports. We will cover that after the jump.


Reports

What is an inventory system good for without some of type of report? In this section, you will learn how to use phpChart – which seamlessly integrates with phpGrid – to create visually pleasing and useful reports for your Inventory Manager application.

Here’s what our page will look like when it’s done:

inventory reports

Before we start, we need to install phpChart. It is recommended that you obtain the full version of phpChart since the free version – phpChart Lite – supports only the line chart.

Setup phpChart

It’s important that we keep phpGrid and phpChart in separate folders. Below is the recommended folder hierarchy.

1
2
3
4
5
6
7
www
+-- Donation_Manager
|   |-- phpGrid
|   |   +-- conf.php
|   |-- phpChart
|   |   +-- conf.php
|   +-- ...

Report Design

We will place a pie chart next to an inventory summary grid. The datagrid provides the series data to plot the pie chart.

Reports UI

phpGrid and phpChart Integration

First of all, include calls to both conf.php files at the beginning of the code.

1
2
require_once("phpGrid/conf.php");
require_once("phpChart/conf.php");

Pie Chart

Below is the complete code to create our pie chart:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 $pc = new C_PhpChartX(array(array(null)), 'PieChart');
$pc->set_title(array('text'=>'Current Inventory Summary'));
$pc->set_series_default(array( 'shadow'=> false,
    'renderer'=> 'plugin::PieRenderer',
    'rendererOptions'=> array(
      'showDataLabels' => true,
      'highlightMouseOver' => true,
      'startAngle'=> 180,
      'sliceMargin'=> 4,
      'showDataLabels'=> true )
  ));
$pc->set_legend(array('show'=>true,'location'=> 'w'));
// remove background
$pc->set_grid(array(
    'background'=>'white',
    'borderWidth'=>0,
    'borderColor'=>'#000000',
    'shadow'=>false));
$pc->add_custom_js("
        $('#PieChart').bind('jqplotDataHighlight',
            function (ev, seriesIndex, pointIndex, data) {
               $('#label_info').text(data);      
            }
        );
    "
);
$pc->draw(660,400);

Let’s walk through the code.

The first line is the constructor. We pass array(null) as the series data because we don’t wish to have any data displayed in the pie chart initially as the inventory data used to plot the chart is not yet available when it is first initialized. The data is fed from the datagrid later in JSON.

We also give our chart a unique name, PieChart.

1
 $pc = new C_PhpChartX(array(array(null)), 'PieChart');

Next, we give it a title. Nothing fancy here.

1
 $pc->set_title(array('text'=>'Current Inventory Summary'));

Once we have the title, we call the series default function to set the renderer to PieRenderer. Unlike a bar chart, a pie chart does not have a Y axis.

We can also set the rendererOptions property. We will not go into each option in detail here, but you can find more information in the online documentation.

1
2
3
4
5
6
7
8
 $pc->set_series_default(array( 'shadow'=> false,
    'renderer'=> 'plugin::PieRenderer',
    'rendererOptions'=> array(
      'highlightMouseOver' => true,
      'startAngle'=> 180,
      'sliceMargin'=> 4,
      'showDataLabels'=> true )
  ));

We also want to show a legend. The set_legend command below shows the legend to the west (noted byw) or to the left of the pie chart.

1
 $pc->set_legend(array('show'=>true,'location'=> 'w'));

We will also remove the border and the background.

1
2
3
4
5
 $pc->set_grid(array(
    'background'=>'white',
    'borderWidth'=>0,
    'borderColor'=>'#000000',
    'shadow'=>false));

Finally, we draw our chart by giving it a height and width in pixels.

1
 $pc->draw(660,400);

However, if you execute the code now, you will not see the chart because the data used to render it isn’t available yet.

Inventory Summary Datagrid

Here, we will use the same the inventory datagrid as we did in the Products page. We just need to add one more thing – an event handler.

In phpGrid, we can add an event handler with the [add_event()] (https://phpgrid.com/documentation/add_event/) function. add_event() binds an event handler, which is essentially a JavaScript function, to a specific phpGrid event. A list of possible events can be found here.

Since we must wait for the datagrid to finish loading before it can send the data to plot the chart, we use the event jqGridLoadComplete.

phpGrid 101 – jqGridLoadComplete Event

jqGridLoadComplete is last event that occurs once the whole datagrid body has finished loading. Note that the grid body will be reloaded if the user changes the sort order of a column or sets a filter.

Send Data Using Javascript

The following is the Javascript event handler for jqGridLoadComplete.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 <span class="hljs-function">function(status, rowid)
{</span>
    var dataX = [];
    var dataY = [];

    d1 = $('#products').jqGrid('getCol', 'ProductLabel', false);
    d2 = $('#products').jqGrid('getCol', 'InventoryReceived', false);

    npoints = d1.length;
    for(var i=0; i < npoints; i++){
        dataX[i] = [i+1, d1[i]];
        dataY[i] = [i+1, parseInt(d2[i])];
    }

    var pieData = [];
    for(var j=0; j < dataX.length; j++)
    {
        pieData.push([dataX[j][1], dataY[j][1]]);
    }
    console.log(pieData);
    _PieChart.series[0].data = pieData;
    _PieChart.replot({resetAxes:true});
}

The complete code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 $dgProd = new C_DataGrid('SELECT id, ProductLabel, InventoryReceived FROM products', 'id', 'products');
$dgProd->set_col_hidden('id', false);
$dgProd->set_dimension('auto', 'auto')->set_pagesize(100);
$onGridLoadComplete = <<<ONGRIDLOADCOMPLETE
function(status, rowid)
{
    var dataX = [];
    var dataY = [];

    d1 = $('#products').jqGrid('getCol', 'ProductLabel', false);
    d2 = $('#products').jqGrid('getCol', 'InventoryReceived', false);
    d3 = $('#products').jqGrid('getCol', 'InventoryShipped', false);
    d4 = $('#products').jqGrid('getCol', 'InventoryOnHand', false);


    npoints = d1.length;
    for(var i=0; i < npoints; i++){
        dataX[i] = [i+1, d1[i]];
        dataY[i] = [i+1, parseInt(d2[i])];
    }

    var pieData = [];
    for(var j=0; j < dataX.length; j++)
    {
        pieData.push([dataX[j][1], dataY[j][1]]);
    }
    console.log(pieData);
    _PieChart.series[0].data = pieData;
    _PieChart.replot({resetAxes:true});
}
ONGRIDLOADCOMPLETE
;
$dgProd->add_event("jqGridLoadComplete", $onGridLoadComplete);
$dgProd->display();

Now there you have it. Your just built your very first inventory management system from scratch using only PHP and MySQL!

Live Demo!

Get this App *

* Included in Ultimate edition.