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.

Also, read:

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.

  • index.php
  • invoice_list.php
  • create_invoice.php
  • edit_invoice.php
  • action.php
  • invoice.js
  • Invoice.php

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.

<div class="row">
<div class="demo-heading pull">
<h2>Build Invoice System with PHP & MySQL</h2>
</div>
<div class="login-form">
<h4>Invoice User Login:</h4>
<form method="post" action="">
<div class="form-group">
<?php if ($loginError ) { ?>
<div class="alert alert-warning"><?php echo $loginError; ?></div>
<?php } ?>
</div>
<div class="form-group">
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" autofocus="" required>
</div>
<div class="form-group">
<input type="password" class="form-control" name="pwd" placeholder="Password" required>
</div>
<div class="form-group">
<button type="submit" name="login" class="btn btn-info">Login</button>
</div>
</form>
</div>
</div>

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


<?php
if (!empty($_POST['email']) && !empty($_POST['pwd'])) {
include 'Invoice.php';
$invoice = new Invoice();
$user = $invoice->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.

<div class="container">
<h2 class="title">PHP Invoice System</h2>
<?php include('menu.php');?>
<table id="data-table" class="table table-condensed table-striped">
<thead>
<tr>
<th>Invoice No.</th>
<th>Create Date</th>
<th>Customer Name</th>
<th>Invoice Total</th>
<th>Print</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<?php
$invoiceList = $invoice->getInvoiceList();
foreach($invoiceList as $invoiceDetails){
$invoiceDate = date("d/M/Y, H:i:s", strtotime($invoiceDetails["order_date"]));
echo '
<tr>
<td>'.$invoiceDetails["order_id"].'</td>
<td>'.$invoiceDate.'</td>
<td>'.$invoiceDetails["order_receiver_name"].'</td>
<td>'.$invoiceDetails["order_total_after_tax"].'</td>
<td><a href="print_invoice.php?invoice_id='.$invoiceDetails["order_id"].'" title="Print Invoice"><span class="glyphicon glyphicon-print"></span></a></td>
<td><a href="edit_invoice.php?update_id='.$invoiceDetails["order_id"].'"  title="Edit Invoice"><span class="glyphicon glyphicon-edit"></span></a></td>
<td><a href="#" id="'.$invoiceDetails["order_id"].'" class="deleteInvoice"  title="Delete Invoice"><span class="glyphicon glyphicon-remove"></span></a></td>
</tr>
';
}
?>
</table>
</div>

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.

<div class="container content-invoice">
<form action="" id="invoice-form" method="post" class="invoice-form" role="form" novalidate="">
<div class="load-animate animated fadeInUp">
<div class="row">
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8">
<h2 class="title">PHP Invoice System</h2>
<?php include('menu.php');?>
</div>
</div>
<input id="currency" type="hidden" value="$">
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<h3>From,</h3>
<?php echo $_SESSION['user']; ?><br>
<?php echo $_SESSION['address']; ?><br>
<?php echo $_SESSION['mobile']; ?><br>
<?php echo $_SESSION['email']; ?><br>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 pull-right">
<h3>To,</h3>
<div class="form-group">
<input type="text" class="form-control" name="companyName" id="companyName" placeholder="Company Name" autocomplete="off">
</div>
<div class="form-group">
<textarea class="form-control" rows="3" name="address" id="address" placeholder="Your Address"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<table class="table table-bordered table-hover" id="invoiceItem">
<tr>
<th width="2%"><input id="checkAll" class="formcontrol" type="checkbox"></th>
<th width="15%">Item No</th>
<th width="38%">Item Name</th>
<th width="15%">Quantity</th>
<th width="15%">Price</th>
<th width="15%">Total</th>
</tr>
<tr>
<td><input class="itemRow" type="checkbox"></td>
<td><input type="text" name="productCode[]" id="productCode_1" class="form-control" autocomplete="off"></td>
<td><input type="text" name="productName[]" id="productName_1" class="form-control" autocomplete="off"></td>
<td><input type="number" name="quantity[]" id="quantity_1" class="form-control quantity" autocomplete="off"></td>
<td><input type="number" name="price[]" id="price_1" class="form-control price" autocomplete="off"></td>
<td><input type="number" name="total[]" id="total_1" class="form-control total" autocomplete="off"></td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
<button class="btn btn-danger delete" id="removeRows" type="button">- Delete</button>
<button class="btn btn-success" id="addRows" type="button">+ Add More</button>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8">
<h3>Notes: </h3>
<div class="form-group">
<textarea class="form-control txt" rows="5" name="notes" id="notes" placeholder="Your Notes"></textarea>
</div>
<br>
<div class="form-group">
<input type="hidden" value="<?php echo $_SESSION['userid']; ?>" class="form-control" name="userId">
<input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-btm">
</div>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<span class="form-inline">
<div class="form-group">
<label>Subtotal:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="subTotal" id="subTotal" placeholder="Subtotal">
</div>
</div>
<div class="form-group">
<label>Tax Rate:  </label>
<div class="input-group">
<input value="" type="number" class="form-control" name="taxRate" id="taxRate" placeholder="Tax Rate">
<div class="input-group-addon">%</div>
</div>
</div>
<div class="form-group">
<label>Tax Amount:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="taxAmount" id="taxAmount" placeholder="Tax Amount">
</div>
</div>
<div class="form-group">
<label>Total:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="totalAftertax" id="totalAftertax" placeholder="Total">
</div>
</div>
<div class="form-group">
<label>Amount Paid:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="amountPaid" id="amountPaid" placeholder="Amount Paid">
</div>
</div>
<div class="form-group">
<label>Amount Due:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="amountDue" id="amountDue" placeholder="Amount Due">
</div>
</div>
</span>
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>

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

<?php
include 'Invoice.php';
$invoice = new Invoice();
$invoice->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.

<div class="container content-invoice">
<form action="" id="invoice-form" method="post" class="invoice-form" role="form" novalidate="">
<div class="load-animate animated fadeInUp">
<div class="row">
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8">
<h1 class="title">PHP Invoice System</h1>
<?php include('menu.php');?>
</div>
</div>
<input id="currency" type="hidden" value="$">
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<h3>From,</h3>
<?php echo $_SESSION['user']; ?><br>
<?php echo $_SESSION['address']; ?><br>
<?php echo $_SESSION['mobile']; ?><br>
<?php echo $_SESSION['email']; ?><br>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 pull-right">
<h3>To,</h3>
<div class="form-group">
<input value="<?php echo $invoiceValues['order_receiver_name']; ?>" type="text" class="form-control" name="companyName" id="companyName" placeholder="Company Name" autocomplete="off">
</div>
<div class="form-group">
<textarea class="form-control" rows="3" name="address" id="address" placeholder="Your Address"><?php echo $invoiceValues['order_receiver_address']; ?></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<table class="table table-bordered table-hover" id="invoiceItem">
<tr>
<th width="2%"><input id="checkAll" class="formcontrol" type="checkbox"></th>
<th width="15%">Item No</th>
<th width="38%">Item Name</th>
<th width="15%">Quantity</th>
<th width="15%">Price</th>
<th width="15%">Total</th>
</tr>
<?php
$count = 0;
foreach($invoiceItems as $invoiceItem){
$count++;
?>
<tr>
<td><input class="itemRow" type="checkbox"></td>
<td><input type="text" value="<?php echo $invoiceItem["item_code"]; ?>" name="productCode[]" id="productCode_<?php echo $count; ?>" class="form-control" autocomplete="off"></td>
<td><input type="text" value="<?php echo $invoiceItem["item_name"]; ?>" name="productName[]" id="productName_<?php echo $count; ?>" class="form-control" autocomplete="off"></td>
<td><input type="number" value="<?php echo $invoiceItem["order_item_quantity"]; ?>" name="quantity[]" id="quantity_<?php echo $count; ?>" class="form-control quantity" autocomplete="off"></td>
<td><input type="number" value="<?php echo $invoiceItem["order_item_price"]; ?>" name="price[]" id="price_<?php echo $count; ?>" class="form-control price" autocomplete="off"></td>
<td><input type="number" value="<?php echo $invoiceItem["order_item_final_amount"]; ?>" name="total[]" id="total_<?php echo $count; ?>" class="form-control total" autocomplete="off"></td>
<input type="hidden" value="<?php echo $invoiceItem['order_item_id']; ?>" class="form-control" name="itemId[]">
</tr>
<?php } ?>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
<button class="btn btn-danger delete" id="removeRows" type="button">- Delete</button>
<button class="btn btn-success" id="addRows" type="button">+ Add More</button>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8">
<h3>Notes: </h3>
<div class="form-group">
<textarea class="form-control txt" rows="5" name="notes" id="notes" placeholder="Your Notes"><?php echo $invoiceValues['note']; ?></textarea>
</div>
<br>
<div class="form-group">
<input type="hidden" value="<?php echo $_SESSION['userid']; ?>" class="form-control" name="userId">
<input type="hidden" value="<?php echo $invoiceValues['order_id']; ?>" class="form-control" name="invoiceId" id="invoiceId">
<input data-loading-text="Updating Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-btm">
</div>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<span class="form-inline">
<div class="form-group">
<label>Subtotal:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="<?php echo $invoiceValues['order_total_before_tax']; ?>" type="number" class="form-control" name="subTotal" id="subTotal" placeholder="Subtotal">
</div>
</div>
<div class="form-group">
<label>Tax Rate:  </label>
<div class="input-group">
<input value="<?php echo $invoiceValues['order_tax_per']; ?>" type="number" class="form-control" name="taxRate" id="taxRate" placeholder="Tax Rate">
<div class="input-group-addon">%</div>
</div>
</div>
<div class="form-group">
<label>Tax Amount:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="<?php echo $invoiceValues['order_total_tax']; ?>" type="number" class="form-control" name="taxAmount" id="taxAmount" placeholder="Tax Amount">
</div>
</div>
<div class="form-group">
<label>Total:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="<?php echo $invoiceValues['order_total_after_tax']; ?>" type="number" class="form-control" name="totalAftertax" id="totalAftertax" placeholder="Total">
</div>
</div>
<div class="form-group">
<label>Amount Paid:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="<?php echo $invoiceValues['order_amount_paid']; ?>" type="number" class="form-control" name="amountPaid" id="amountPaid" placeholder="Amount Paid">
</div>
</div>
<div class="form-group">
<label>Amount Due:  </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="<?php echo $invoiceValues['order_total_amount_due']; ?>" type="number" class="form-control" name="amountDue" id="amountDue" placeholder="Amount Due">
</div>
</div>
</span>
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>

We will edit save invoice using invoice method updateInvoice()


<?php
include 'Invoice.php';
$invoice = new Invoice();
$invoice->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.

<?php
session_start();
include 'Invoice.php';
$invoice = new Invoice();
$invoice->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 .= '<table width="100%" border="1" cellpadding="5" cellspacing="0">
<tr>
<td colspan="2" align="center" style="font-size:18px"><b>Invoice</b></td>
</tr>
<tr>
<td colspan="2">
<table width="100%" cellpadding="5">
<tr>
<td width="65%">
To,<br />
<b>RECEIVER (BILL TO)</b><br />
Name : '.$invoiceValues['order_receiver_name'].'<br />
Billing Address : '.$invoiceValues['order_receiver_address'].'<br />
</td>
<td width="35%">
Invoice No. : '.$invoiceValues['order_id'].'<br />
Invoice Date : '.$invoiceDate.'<br />
</td>
</tr>
</table>
<br />
<table width="100%" border="1" cellpadding="5" cellspacing="0">
<tr>
<th align="left">Sr No.</th>
<th align="left">Item Code</th>
<th align="left">Item Name</th>
<th align="left">Quantity</th>
<th align="left">Price</th>
<th align="left">Actual Amt.</th>
</tr>';
$count = 0;
foreach($invoiceItems as $invoiceItem){
$count++;
$output .= '
<tr>
<td align="left">'.$count.'</td>
<td align="left">'.$invoiceItem["item_code"].'</td>
<td align="left">'.$invoiceItem["item_name"].'</td>
<td align="left">'.$invoiceItem["order_item_quantity"].'</td>
<td align="left">'.$invoiceItem["order_item_price"].'</td>
<td align="left">'.$invoiceItem["order_item_final_amount"].'</td>
</tr>';
}
$output .= '
<tr>
<td align="right" colspan="5"><b>Sub Total</b></td>
<td align="left"><b>'.$invoiceValues['order_total_before_tax'].'</b></td>
</tr>
<tr>
<td align="right" colspan="5"><b>Tax Rate :</b></td>
<td align="left">'.$invoiceValues['order_tax_per'].'</td>
</tr>
<tr>
<td align="right" colspan="5">Tax Amount: </td>
<td align="left">'.$invoiceValues['order_total_tax'].'</td>
</tr>
<tr>
<td align="right" colspan="5">Total: </td>
<td align="left">'.$invoiceValues['order_total_after_tax'].'</td>
</tr>
<tr>
<td align="right" colspan="5">Amount Paid:</td>
<td align="left">'.$invoiceValues['order_amount_paid'].'</td>
</tr>
<tr>
<td align="right" colspan="5"><b>Amount Due:</b></td>
<td align="left">'.$invoiceValues['order_total_amount_due'].'</td>
</tr>';
$output .= '
</table>
</td>
</tr>
</table>';
// 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 id = $(this).attr("id");
if(confirm("Are you sure you want to remove this?")){
$.ajax({
url:"action.php",
method:"POST",
dataType: "json",
data:{id:id, action:'delete_invoice'},
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.

<?php
include 'Invoice.php';
$invoice = new Invoice();
if($_POST['action'] == 'delete_invoice' && $_POST['id']) {
$invoice->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

<?php
if($_GET['action'] == 'logout') {
session_unset();
session_destroy();
header("Location:index.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.


<?php
public function loginUsers($email, $password){
$sqlQuery = "
SELECT id, email, first_name, last_name, address, mobile
FROM ".$this->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

186 thoughts on “Build Invoice System with PHP & MySQL

  1. Ok I don’t know if I’m doing something wrong or not, but when I’m unable to login! I put this on localhost, created the DB, added necessary tables then added a user in the ‘invoice_user’ table. Using the email and password in ‘invoice_user’ I’m unable to login! Please help

    1. Please check method getData() in Invoice.php and replace MYSQL_ASSOC with MYSQLI_ASSOC. Thanks!

  2. Amazing Code and exactly what I need! I am however struggling with logging in after setting up everything. I inserted a user in the invoice_user table but for some reason the email and password seem to be invalid. Could you please help? Or at least can you share an export of the DB? Best regards and many thanks once again!

    1. Please check if there any error or warning user in method getData() in Invoice.php. Replace MYSQL_ASSOC with MYSQLI_ASSOC. Thanks!

  3. Demo not work, please fix it please:
    Error failed to connect to MySQL: Access denied for user ‘codewit8_zagdemo’@’localhost’ (using password: YES)
    How to loget in my locahost account xampp?
    How to created login data for login?
    please help me!

    thanks a lot

  4. Hi,
    Nice tutorial. I did like you and it works locally in my wampserver, but when i upload my files online to my server it stops working. The file index.php for authentification doesn’nt work with my database online despite the fact that i enter the correct data in the sign in form.
    How can i fix it ?

  5. I am connected to DB with user and password.

    When i fill out invoice information and press create invoice. I am directed to invoice list, but its still empty.
    Checking MYSQL no information is added to the databases?

    No error showing.

  6. I figured it out.
    You have to change any MYSQL to MYSQLI.
    The invoice_order database needs an auto increment and order_id (and most other integer columns) needs to SET NOT NULL DEFAULT to 0 if your having issues still.

  7. I have tried the steps but it doesn’t work. I don’t see the database name (only names of table provided). Also, the PHP code to connect the database to the PHP pages is not available.

    Any advice on this?

      1. Fatal error: Uncaught Dompdf\Exception: file_get_contents(): Passing null to parameter #2 ($use_include_path) of type bool is deprecated

    1. Hi It’s working , but what you have to do is that when you enter invoice Item and qty after just fill the Paid Amount field in the right bottom corner , and click save you will see that it works fine.

  8. i have downloaded from the link but the invoice is not saving and not showing in invoice list.please help.

    1. have made invoice order_id and order_item_id field as auto increment? if not please do that. then check it. Thanks!

  9. Hi Guys, for those who has the problem with “Invoice not saving” because you have not entered the paid amount field with a value. Just try saving the invoice after filling the invoice paid amount field. It made me number of workaround to go through and found this working.

    Good Day buddies

  10. Hi, great work. I created the tables, downloaded the pages, updated DB info for my build, index page will not pass username and password. On submit I get a messages that “page isnt working” “10.0.0.20 is currently unable to handle this request.” any ideas? I did make sure to change all MYSQL to MSQLI in Invoice.php. thanks, Dave

  11. HOW TO SOLVE THIS ERROR
    – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
    Warning: mysqli_error() expects exactly 1 parameter, 0 given in G:\xampp\htdocs\build-invoice-demo\Invoice.php on line 24
    Error in query:
    – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
    PLEASE TELL ME SOLUTION

  12. HI, there i want to use it with Laravel Framework can you guide me throught …as it is giving error in invoice.js

  13. Hi,

    Thanks so much for great tutorial …
    I have tried the online demo, but on clicking “Print” invoice, this message displayed:
    “5Unable to stream pdf: headers already sent”

      1. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

  14. Just getting this error :

    Parse error: syntax error, unexpected ‘Public’ (T_PUBLIC), expecting end of file in C:\wamp64\www\Invoice\Invoice.php on line 3

    Please I need Help

  15. Dear friend, a huge thanks for this tutorial, where can we download the complete project for all files? openend DEMO but theres no downlaod there

  16. dear, all system works but when i make edit on invoice it makes double the order item when i click sale invoice, thnks

    1. Have you tried to debug the code to find the cause of issue? plz try it , if still face issue. you can share the code to fix issue. thanks!

  17. hi, just wanne say i love the program. i have a small issue with it. when i create an new invoice it works fine but when i want to edit one it opens an empty page

    i checked the database and the order_item_id and order_id have only 0’s in them

  18. I can’t save the invoice. When I had finished the capture I press the Save button and disappear all the lines. Could you help me, please?

  19. Nice one guys, I am able to fix all the errors but only printing of invoice seems to prove stubborn, can you pls shed more light

  20. Hi,
    Great system, just encountering one issue (cant see anyone else having this problem in the comments)

    when i go to print, items are showing but the values and and customer address and name not showing
    looks like an issue with print_invoice.php
    if(!empty($_GET[‘invoice_id’]) && $_GET[‘invoice_id’] ) {

    echo $_GET[‘invoice_id’];
    $invoiceItems = $invoice->getInvoiceItems($_GET[‘invoice_id’]);
    $invoiceValues = $invoice->getInvoice($_GET[‘invoice_id’]); <—— This part
    }

    is there anything i can do to fix it?

    thanks

  21. Hello my Invoice page doesn’t load after logging in it keeps on saying invalid email and password please advice
    But thanks for this Tutorial

  22. I have tried a log to fix the login error but everytime I am trying to login using user name and password I simply cannot

    connection data is correct, I have inserted login data manually into database, ID is auto increment but still no success

  23. Thank you, but I’m getting the error “Warning: Cannot modify header information – headers already sent by (output started at /sata2/home/users/****/header.php:1) in /sata2/home/users/****/index.php on line 15

  24. When i try to print the invoice it is telling the below error,

    Error
    Failed to load PDF document

  25. Hi,

    I hope you can be able to help me.

    As per checking, and testing base on your code, when I go to Invoice Lists and Click the Edit Button, there is an error showing:

    Notice: Undefined variable: invoiceItems in C:\xampp\htdocs\DotMobile_02\edit_invoice.php on line 62

    Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\DotMobile_02\edit_invoice.php on line 62

    This is under the Edit_Invoice.php

    I hope you can be able to help me. thanks

  26. hello dear thanks to upload invoice system in php and mysql
    i enter user information i cannot logged in.

    Warning: Use of undefined constant MYSQL_ASSOC – assumed ‘MYSQL_ASSOC’ (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\build-invoice\Invoice.php on line 27

    Warning: mysqli_fetch_array() expects parameter 2 to be integer, string given in C:\xampp\htdocs\build-invoice\Invoice.php on line 27
    This is error which i face when i try it.
    Waiting for you anticipating response.
    Regards
    Muhammad Naeem Raza

  27. Sir amazing work i am facing 2 difficulties
    1. The invoice NO. is not increasing
    2. Print is not working
    Thanks a Lot

  28. wot a great script, just one thing, wot about if one or two items would have discount for example item 1: price 500.00 discount 200 total 300
    item 2 : price 600 discount 100 total 500

    how add this option

        1. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

    1. Now it is working fine, I had to auto increment order_id and order_item_id and make them primary key

      Thanks,

    2. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

  29. HI first of all thankss i m looking for this project
    but, i dont know how to run this all project and how to give live demo of this project
    to check its working
    ineeed some guide like list of all things to install in my computer
    and how to run thi hole project
    also i m using xampp and vs code editor pls guide me to run this project in my computer

    1. Your comment is awaiting moderation.
      HI first of all thankss i m looking for this project
      but, i dont know how to run this all project and how to give live demo of this project
      to check its working
      ineeed some guide like list of all things to install in my computer
      and how to run thi hole project
      also i m using xampp and vs code editor pls guide me to run this project in my computer

    2. Just download project and run through xampp same as running other projects like (create database, create tables and edit dstabase connection details) etc. thanks!

    1. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

  30. its working sir, but its can’t save to invoice_order database table. and not display in invoice_list
    thanks!

    1. have you set order id autoincrement in invoice_order table ? if not please set and then try. Thanks!

  31. Hi Ive tried to insert manually the user and password but still i cannot login how can i fix this? I use md5 for the password but still not working

  32. How can i remove login from the script? Because I need to integrate this with my existing project. Thanks in advance.

    1. You can easily modify the project file as per your need. Just check login code and remove from everywhere as per your requirement. thanks!

  33. please also in your demo when printing invoice:
    1Unable to stream pdf: headers already sent.
    Can you give us the reason. thanks

    1. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

    1. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

    1. You need to use ob_start(); before session_start() in file print_invoice.php. it is updated in demo. thanks!

  34. Hi I inserted manually the user and password but still i cannot login how can i fix this? I use md5 for the password but still not working

  35. Thanks for this great site, I learned a lot here! This tutorial is also good and very helpful.
    But when I click on the Demo or Download button I am redirected to various websites that require me to sign up for push notifications, then I am redirected again to a page where I should register or buy vpn or games … Is this intentional or are you the victim of an attack?

    How can I normally view demo and download files?

    Regards

  36. There is some issue. I am not able to download the project. kindly provide me direct download link.

    Thanks

  37. Hello Bro,

    Many thanks for the nice code

    I have issue during press on print pdf icon I got error 520 on my page, and I think because of this line : “require_once ‘dompdf/src/Autoloader.php’;”

    what could be the issue?

    I am using hostinger domain
    Any help please

  38. hello. thanks for codes. i want use it but i have very long invoices. i cant convert my invoices 3 or 4 pages pdf. how can i make it.

  39. Hello,

    I’d like to include a logo when the invoice is printed to pdf.
    I’d appreciate your instructions on how to achieve that

  40. its really wonderful if you can teach me how to do each item can have discount, subtotal and total.
    i really appreciate that if possible,

  41. Showing Error:
    2
    Fatal error: Uncaught Dompdf\Exception: file_get_contents(): Passing null to parameter #2 ($use_include_path) of type bool is deprecated 8192 in C:\xampp\htdocs\project3\invoice-system-php\dompdf\src\Helpers.php:507 Stack trace: #0 [internal function]: Dompdf\Helpers::record_warnings(8192, ‘file_get_conten…’, ‘C:\\xampp\\htdocs…’, 839) #1 C:\xampp\htdocs\project3\invoice-system-php\dompdf\src\Helpers.php(839): file_get_contents(‘C:\\xampp\\htdocs…’, NULL, NULL, 0) #2 C:\xampp\htdocs\project3\invoice-system-php\dompdf\src\Css\Stylesheet.php(367): Dompdf\Helpers::getFileContent(‘C:\\xampp\\htdocs…’, NULL) #3 C:\xampp\htdocs\project3\invoice-system-php\dompdf\src\Dompdf.php(572): Dompdf\Css\Stylesheet->load_css_file(‘C:\\xampp\\htdocs…’, 1) #4 C:\xampp\htdocs\project3\invoice-system-php\dompdf\src\Dompdf.php(724): Dompdf\Dompdf->processHtml() #5 C:\xampp\htdocs\project3\invoice-system-php\print_invoice.php(94): Dompdf\Dompdf->render() #6 {main} thrown in C:\xampp\htdocs\project3\invoice-system-php\dompdf\src\Helpers.php on line 507

  42. \invoice-system-php\dompdf\src\Helpers.php on line 507

    i click the pdf button and this error display. Can u help me please!!

Leave a Reply

Your email address will not be published. Required fields are marked *