Build Invoice System with PHP & MySQL

In our previous tutorial, we have explained how to develop Inventory System with Ajax, PHP & MySQL. In this tutorial, we will explain how to develop your own invoice system with PHP and MySQL.

Invoice or Billing Management Systems are very popular as now most of transactions are done online. Now every sellers and buyers needs invoice system to handle billing online. So if you’re looking for invoice or billing system using PHP and MySQL, then you’re here at right place. In this tutorial you will learn how to develop invoice and billing system using PHP and MySQL.

We will cover this tutorial in easy steps with live demo to develop complete invoice system to create and edit invoices with invoice print to convert into PDF format. We will also allow to download complete source code of live demo.

As we will cover this tutorial with live example to build invoice system with PHP & MySQL, so the major files for this example is following.

Step1: Create MySQL Database Tables
First we will create table invoice_user to store user login details to allow logged in user to manage invoices.

CREATE TABLE `invoice_user` ( `id` int(11) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, `mobile` bigint(20) NOT NULL, `address` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `invoice_user` ADD PRIMARY KEY (`id`); ALTER TABLE `invoice_user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=123457;

Here is the sample user dump data:

INSERT INTO `invoice_user` (`id`, `email`, `password`, `first_name`, `last_name`, `mobile`, `address`) VALUES (123456, 'admin@phpzag.com', '12345', 'Admin', '', 12345678912, 'New Delhi 110096 India.');

We will create table invoice_order to store invoice details.

CREATE TABLE `invoice_order` ( `order_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `order_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `order_receiver_name` varchar(250) NOT NULL, `order_receiver_address` text NOT NULL, `order_total_before_tax` decimal(10,2) NOT NULL, `order_total_tax` decimal(10,2) NOT NULL, `order_tax_per` varchar(250) NOT NULL, `order_total_after_tax` double(10,2) NOT NULL, `order_amount_paid` decimal(10,2) NOT NULL, `order_total_amount_due` decimal(10,2) NOT NULL, `note` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `invoice_order` ADD PRIMARY KEY (`order_id`); ALTER TABLE `invoice_order` MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=682;

Here is sample dump data for invoice order:

INSERT INTO `invoice_order` (`order_id`, `user_id`, `order_date`, `order_receiver_name`, `order_receiver_address`, `order_total_before_tax`, `order_total_tax`, `order_tax_per`, `order_total_after_tax`, `order_amount_paid`, `order_total_amount_due`, `note`) VALUES (2, 123456, '2021-01-31 19:33:42', 'abcd', 'Admin\r\nA - 4000, Ashok Nagar, New Delhi, 110096 India.\r\n12345678912\r\nadmin@phpzag.com', 342400.00, 684800.00, '200', 1027200.00, 45454.00, 981746.00, 'this note txt');

We will also create table invoice_order_item to store invoice items details.

CREATE TABLE `invoice_order_item` ( `order_item_id` int(11) NOT NULL, `order_id` int(11) NOT NULL, `item_code` varchar(250) NOT NULL, `item_name` varchar(250) NOT NULL, `order_item_quantity` decimal(10,2) NOT NULL, `order_item_price` decimal(10,2) NOT NULL, `order_item_final_amount` decimal(10,2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `invoice_order_item` ADD PRIMARY KEY (`order_item_id`); ALTER TABLE `invoice_order_item` MODIFY `order_item_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4364;

Here is sample dump data for invoice order items:

INSERT INTO `invoice_order_item` (`order_item_id`, `order_id`, `item_code`, `item_name`, `order_item_quantity`, `order_item_price`, `order_item_final_amount`) VALUES (4100, 2, '13555', 'Face Mask', 120.00, 2000.00, 240000.00), (4101, 2, '34', 'mobile', 10.00, 10000.00, 100000.00), (4102, 2, '34', 'mobile battery', 1.00, 34343.00, 34343.00), (4103, 2, '34', 'mobile cover', 10.00, 200.00, 2000.00), (4104, 2, '36', 'testing', 1.00, 2400.00, 2400.00);

Step2: Implement User Login
First we will create user login functionality to provide invoice manage access to logged in users. We will create login form in index.php.

 

Build Invoice System with PHP & MySQL

Invoice User Login:

?>

We will handle login functionality on login form submit using method loginUsers().

loginUsers($_POST['email'], $_POST['pwd']); if(!empty($user)) < $_SESSION['user'] = $user[0]['first_name']."".$user[0]['last_name']; $_SESSION['userid'] = $user[0]['id']; $_SESSION['email'] = $user[0]['email']; $_SESSION['address'] = $user[0]['address']; $_SESSION['mobile'] = $user[0]['mobile']; header("Location:invoice_list.php"); >else < $loginError = "Invalid email or password!"; >> ?>

Step3: Display Invoice List
Now we will display user’s invoices list in invoice_list.php file. We will call invoice method getInvoiceList() to get list logged in user’s invoices list.

 

PHP Invoice System

getInvoiceList(); foreach($invoiceList as $invoiceDetails) < $invoiceDate = date("d/M/Y, H:i:s", strtotime($invoiceDetails["order_date"])); echo ' '; > ?>
Invoice No. Create Date Customer Name Invoice Total Print Edit Delete
'.$invoiceDetails["order_id"].' '.$invoiceDate.' '.$invoiceDetails["order_receiver_name"].' '.$invoiceDetails["order_total_after_tax"].'

Step4: Implement Invoice Create
Now in create_invoice.php, we will implement functionality to create invoice. We will create invoice form with required fields to save invoice details with items and totals.

 

PHP Invoice System

From,




To,

Item No Item Name Quantity Price Total

Notes:


" name="userId">
$
%
$
$
$
$

We will save invoice details using invoice method saveInvoice().

saveInvoice($_POST); ?>

Step5: Implement Invoice Update
Now in edit_invoice.php, we will implement functionality to edit invoice. We will create invoice form with required fields to save invoice edit details with items and totals.

 

PHP Invoice System

From,




To,

" type="text" name="companyName" placeholder="Company Name" autocomplete="off">
" name="itemId[]"> ?>
Item No Item Name Quantity Price Total
" name="productCode[]" autocomplete="off"> " name="productName[]" autocomplete="off"> " name="quantity[]" autocomplete="off"> " name="price[]" autocomplete="off"> " name="total[]" autocomplete="off">

Notes:


" name="userId"> " name="invoiceId" >
$
" type="number" name="subTotal" placeholder="Subtotal">
" type="number" name="taxRate" placeholder="Tax Rate">
%
$
" type="number" name="taxAmount" placeholder="Tax Amount">
$
" type="number" name="totalAftertax" placeholder="Total">
$
" type="number" name="amountPaid" placeholder="Amount Paid">
$
" type="number" name="amountDue" placeholder="Amount Due">

We will edit save invoice using invoice method updateInvoice()

updateInvoice($_POST); ?>

Step6: Implement Invoice Print
Now we will implement functionality to create invoice PDF in print_invoice.php file to allow user to print or download invoice. We will get invoice details from database tables using invoice method getInvoice() and getInvoiceItems(). Then we will use PHP library Dompdf to create PDF from HTML.

checkLoggedIn(); if(!empty($_GET['invoice_id']) && $_GET['invoice_id']) < echo $_GET['invoice_id']; $invoiceValues = $invoice->getInvoice($_GET['invoice_id']); $invoiceItems = $invoice->getInvoiceItems($_GET['invoice_id']); > $invoiceDate = date("d/M/Y, H:i:s", strtotime($invoiceValues['order_date'])); $output = ''; $output .= ' 
Invoice
To,
RECEIVER (BILL TO)
Name : '.$invoiceValues['order_receiver_name'].'
Billing Address : '.$invoiceValues['order_receiver_address'].'
Invoice No. : '.$invoiceValues['order_id'].'
Invoice Date : '.$invoiceDate.'

'; $count = 0; foreach($invoiceItems as $invoiceItem) < $count++; $output .= ' '; > $output .= ' '; $output .= '
Sr No. Item Code Item Name Quantity Price Actual Amt.
'.$count.' '.$invoiceItem["item_code"].' '.$invoiceItem["item_name"].' '.$invoiceItem["order_item_quantity"].' '.$invoiceItem["order_item_price"].' '.$invoiceItem["order_item_final_amount"].'
Sub Total '.$invoiceValues['order_total_before_tax'].'
Tax Rate : '.$invoiceValues['order_tax_per'].'
Tax Amount: '.$invoiceValues['order_total_tax'].'
Total: '.$invoiceValues['order_total_after_tax'].'
Amount Paid: '.$invoiceValues['order_amount_paid'].'
Amount Due: '.$invoiceValues['order_total_amount_due'].'
'; // create pdf of invoice $invoiceFileName = 'Invoice-'.$invoiceValues['order_id'].'.pdf'; require_once 'dompdf/src/Autoloader.php'; Dompdf\Autoloader::register(); use Dompdf\Dompdf; $dompdf = new Dompdf(); $dompdf->loadHtml(html_entity_decode($output)); $dompdf->setPaper('A4', 'landscape'); $dompdf->render(); $dompdf->stream($invoiceFileName, array("Attachment" => false)); ?>

Step7: Implement Invoice Delete
We will implement invoice delete functionality in invoice.js. We will handle functionality on deleteInvoice handler and make Ajax request to action.php to delete invoice from database table.

$(document).on('click', '.deleteInvoice', function()< var you sure you want to remove this?"))< $.ajax(< url:"action.php", method:"POST", dataType: "json", data:, success:function(response) < if(response.status == 1) < $('#'+id).closest("tr").remove(); >> >); > else < return false; >>);

In action.php, we will check for delete invoice action and invoice id to delete invoice using invoice method deleteInvoice() and return JSON response.

deleteInvoice($_POST['id']); $jsonResponse = array( "status" => 1 ); echo json_encode($jsonResponse); > ?>

Step8: Implement User Logout
We will also implement user logout functionality by passing action logout to action.php

Step9: Complete Invoice Module with Method
We will create MySQL database connection and all methods in Invoice.php. Here is complete list of invoice methods.

invoiceUserTable." WHERE email='".$email."' AND password='".$password."'"; return $this->getData($sqlQuery); > public function checkLoggedIn() < if(!$_SESSION['userid']) < header("Location:index.php"); >> public function saveInvoice($POST) < $sqlInsert = " INSERT INTO ".$this->invoiceOrderTable."(user_id, order_receiver_name, order_receiver_address, order_total_before_tax, order_total_tax, order_tax_per, order_total_after_tax, order_amount_paid, order_total_amount_due, note) VALUES ('".$POST['userId']."', '".$POST['companyName']."', '".$POST['address']."', '".$POST['subTotal']."', '".$POST['taxAmount']."', '".$POST['taxRate']."', '".$POST['totalAftertax']."', '".$POST['amountPaid']."', '".$POST['amountDue']."', '".$POST['notes']."')"; mysqli_query($this->dbConnect, $sqlInsert); $lastInsertId = mysqli_insert_id($this->dbConnect); for ($i = 0; $i < count($POST['productCode']); $i++) < $sqlInsertItem = " INSERT INTO ".$this->invoiceOrderItemTable."(order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount) VALUES ('".$lastInsertId."', '".$POST['productCode'][$i]."', '".$POST['productName'][$i]."', '".$POST['quantity'][$i]."', '".$POST['price'][$i]."', '".$POST['total'][$i]."')"; mysqli_query($this->dbConnect, $sqlInsertItem); > > public function updateInvoice($POST) < if($POST['invoiceId']) < $sqlInsert = " UPDATE ".$this->invoiceOrderTable." SET order_receiver_name = '".$POST['companyName']."', order_receiver_address= '".$POST['address']."', order_total_before_tax = '".$POST['subTotal']."', order_total_tax = '".$POST['taxAmount']."', order_tax_per = '".$POST['taxRate']."', order_total_after_tax = '".$POST['totalAftertax']."', order_amount_paid = '".$POST['amountPaid']."', order_total_amount_due = '".$POST['amountDue']."', note = '".$POST['notes']."' WHERE user_id = '".$POST['userId']."' AND order_id = '".$POST['invoiceId']."'"; mysqli_query($this->dbConnect, $sqlInsert); > $this->deleteInvoiceItems($POST['invoiceId']); for ($i = 0; $i < count($POST['productCode']); $i++) < $sqlInsertItem = " INSERT INTO ".$this->invoiceOrderItemTable."(order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount) VALUES ('".$POST['invoiceId']."', '".$POST['productCode'][$i]."', '".$POST['productName'][$i]."', '".$POST['quantity'][$i]."', '".$POST['price'][$i]."', '".$POST['total'][$i]."')"; mysqli_query($this->dbConnect, $sqlInsertItem); > > public function getInvoiceList()< $sqlQuery = " SELECT * FROM ".$this->invoiceOrderTable." WHERE user_id = '".$_SESSION['userid']."'"; return $this->getData($sqlQuery); > public function getInvoice($invoiceId)< $sqlQuery = " SELECT * FROM ".$this->invoiceOrderTable." WHERE user_id = '".$_SESSION['userid']."' AND order_id = '$invoiceId'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $row = mysqli_fetch_array($result, MYSQL_ASSOC); return $row; > public function getInvoiceItems($invoiceId)< $sqlQuery = " SELECT * FROM ".$this->invoiceOrderItemTable." WHERE order_id = '$invoiceId'"; return $this->getData($sqlQuery); > public function deleteInvoiceItems($invoiceId)< $sqlQuery = " DELETE FROM ".$this->invoiceOrderItemTable." WHERE order_id = '".$invoiceId."'"; mysqli_query($this->dbConnect, $sqlQuery); > public function deleteInvoice($invoiceId)< $sqlQuery = " DELETE FROM ".$this->invoiceOrderTable." WHERE order_id = '".$invoiceId."'"; mysqli_query($this->dbConnect, $sqlQuery); $this->deleteInvoiceItems($invoiceId); return 1; > ?>

You may also like:

You can view the live demo from the Demo link and can download the full script from the Download link below.
Demo Download