Php

Invoice Management System Using PHP & MySQL

in this post, We will explain how to create your own invoice system with PHP & MySQL.It’s also called Billing Management Systems, we’ll create invoice, list all invoices and print invoice.

I am extending my previous tutorials. I’ll add an invoice management system.

What’s Invoice Management Systems

Because the majority of transactions are now done online, invoice or billing management systems are increasingly popular. Every vendor and buyer now requires an invoicing system to manage online billing.

in this article, we’ll cover following functionalities:

  • Create a new Invoice
  • Edit a Invoice
  • Listing invoice
  • Print Invoice

Create Billing Management Systems

Let’s create a PHP project to develop invoice and billing system using PHP and MySQL.I am extending previous tutorial Create Admin Login and Logout Page.

The above post will have normal login as well as admin, I am just using the above source code and functionality.

This article will walk you through the process of creating a full invoice system, including how to create and edit invoices, as well as how to print invoices and convert them to PDF format. We will also make the source code available for download.

Database changes

I’ll update login table, I have added new mobile column into the ‘login’ table:

`mobile` varchar(255) DEFAULT NULL,
I have created two tables for order and order_details:

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `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;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`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
(684, 1, '2021-11-15 15:33:26', '1', 'test', '157.00', '0.00', '', 157.00, '0.00', '157.00', '');

-- --------------------------------------------------------

--
-- Table structure for table `order_details`
--

CREATE TABLE `order_details` (
  `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;

--
-- Dumping data for table `order_details`
--

INSERT INTO `order_details` (`order_item_id`, `order_id`, `item_code`, `item_name`, `order_item_quantity`, `order_item_price`, `order_item_final_amount`) VALUES
(4368, 684, '1', 'test', '1.00', '45.00', '45.00'),
(4369, 684, '3', 'test2', '2.00', '56.00', '112.00');

The files & folders structure for invoice management:

We’ll create an invoice module in the admin folder.

Let’s create the above blank files:

admin/ajax_admin.php : This file contains admin ajax logic.
invoice/action.php : It contains all actions method that will fetach invloices,create,edit and delete method.
invoice/create.php : The HTML UI for add a invoice.
invoice/edit.php : The HTML UI for editing a invoice.
invoice/index.php : The HTML UI for listing all invoices.
invoice/print.php : The HTML UI to display invoice details and print.

Create Invoice Form

Open create.php file and added below HTML code into this file.I have included all files that need to use to create a new invoice.

Related Post
<?php 
include_once("../../header.php"); 
include_once("../../account.php"); 
if (!isAdmin()) {
 $_SESSION['msg'] = "You must log in first";
 header('location: ../../login.php');
}
if (isset($_GET['logout'])) {
 session_destroy();
 unset($_SESSION['user_info']);
 header("location: ../../login.php");
}
include 'action.php';
$invoice = new Invoice();
if(!empty($_POST['companyName']) && $_POST['companyName']) { 
 $invoice->saveInvoice($_POST);
 header("Location:index.php"); 
}
?>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">
        
        <?php include_once("../../sidebar.php"); ?>

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">
                <?php include_once("../../top_navbar.php");?>
                <!-- Begin Page Content -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                    <h1 class="h3 mb-4 text-gray-800">Create an Invoice</h1>
                    <form action-xhr="#" id="invoice-form" method="post" class="invoice-form" role="form" novalidate="">
                <div class="load-animate animated fadeInUp">
                <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_info']['first_name'].' '.$_SESSION['user_info']['last_name']; ?><br>
                <?php echo 'delh, India' ?><br>
                <?php echo $_SESSION['user_info']['mobile']; ?><br>
                <?php echo $_SESSION['user_info']['email']; ?><br>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 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-7 col-md-7 col-lg-7">
                <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['user_info']['id']; ?>" 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-5 col-md-5 col-lg-5">
                <span class="form-inline">
                <div class="form-group">
                <label>Subtotal:($)  </label>
                <div class="input-group">
                <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>
                </div>
                <div class="form-group">
                <label>Tax Amount:($)  </label>
                <div class="input-group">
                <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">
                <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">
                <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">
                <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>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->
    <?php
include_once("../../footer.php"); 
?>

PHP method To Create a new invoice

Let’s add the below code into the action.php file:

include_once("../../db/connection.php");
class Invoice{
    private $invoiceOrderTable = 'orders';
    private $invoiceOrderItemTable = 'order_details';
    private $dbConnect = false;
    
    public function __construct(){
        $db = new dbObj();
        $this->dbConnect =  $db->getConnstring();
    }

    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);
        }
    }
}

Listing all invoices

Let’s create a listing of all invoices into the index.php file, also create methods to get data from database. The getInvoiceList() to get list logged in user’s invoices list.

<?php 
include_once("../../header.php"); 
include_once("../../account.php");
 
if (!isAdmin()) {
 $_SESSION['msg'] = "You must log in first";
 header('location: ../../login.php');
}
if (isset($_GET['logout'])) {
 session_destroy();
 unset($_SESSION['user_info']);
 header("location: ../../login.php");
}
include 'action.php';
$invoice = new Invoice();
?>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">
        
        <?php include_once("../../sidebar.php"); ?>

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

            <?php include_once("../../top_navbar.php");?>

                <!-- Begin Page Content -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                    <h1 class="h3 mb-4 text-gray-800">PHP Invoice System</h1>
                    <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>Action</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="admin/invoice/print.php?invoice_id='.$invoiceDetails["order_id"].'" class="btn btn-info btn-circle"  title="Print Invoice"><span class="fas fa-print"></span></a>
                        <a href="admin/invoice/edit.php?update_id='.$invoiceDetails["order_id"].'" class="btn btn-info btn-circle"  title="Edit Invoice"><span class="fas fa-edit"></span></a>
                        <a href="javascript:void(0)" id="'.$invoiceDetails["order_id"].'" class="deleteInvoice btn btn-danger btn-circle"  title="Delete Invoice"><span class="fas fa-trash"></span></a></td>
                        </tr>
                        ';
                        }
                        ?>
                    </table>    
<?php
include_once("../../footer.php");
?>

We have also added action methods to edit, print and delete invoices.

Action method to get All invoices

Let’s add the below methods into the action.php file:

    private function getData($sqlQuery) {
        $result = mysqli_query($this->dbConnect, $sqlQuery);
        if(!$result){
            die('Error in query: '. mysqli_error($this->dbConnect));
        }
        $data= array();
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $data[]=$row;            
        }
        return $data;
    }
 public function getInvoiceList(){
        $sqlQuery = "
            SELECT * FROM ".$this->invoiceOrderTable." 
            WHERE user_id = '".$_SESSION['user_info']['id']."'";
        return  $this->getData($sqlQuery);
    }

Edit an Invoice

Let’s create a edit UI and php method to update existing invoice. open edit.php file and added below code:

<?php 
include_once("../../header.php"); 
include_once("../../account.php"); 
if (!isAdmin()) {
 $_SESSION['msg'] = "You must log in first";
 header('location: ../../login.php');
}
if (isset($_GET['logout'])) {
 session_destroy();
 unset($_SESSION['user_info']);
 header("location: ../../login.php");
}
include 'action.php';
$invoice = new Invoice();
if(!empty($_GET['update_id']) && $_GET['update_id']) {
    $invoiceValues = $invoice->getInvoice($_GET['update_id']);
    $invoiceItems = $invoice->getInvoiceItems($_GET['update_id']);
}
if(!empty($_POST['invoice_btn']) && $_POST['invoice_btn']) {
    $invoice->updateInvoice($_POST);
}
?>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">
        
        <?php include_once("../../sidebar.php"); ?>

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">
                <?php include_once("../../top_navbar.php");?>
                <!-- Begin Page Content -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                    <h1 class="h3 mb-4 text-gray-800">Create an Invoice</h1>
                    <form action-xhr="#" id="invoice-form" method="post" class="invoice-form" role="form" novalidate="">
<div class="load-animate animated fadeInUp">

<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_info']['first_name'].' '.$_SESSION['user_info']['last_name']; ?><br>
<?php echo 'delh, India' ?><br>
<?php echo $_SESSION['user_info']['mobile']; ?><br>
<?php echo $_SESSION['user_info']['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['user_info']['id']; ?>" 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>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->
    <?php
include_once("../../footer.php"); 
?>

PHP method To Update an invoice

Let’s add the below code into the action.php file:

public function getInvoice($invoiceId){
        $sqlQuery = "
            SELECT * FROM ".$this->invoiceOrderTable." 
            WHERE user_id = '".$_SESSION['user_info']['id']."' AND order_id = '$invoiceId'";
        $result = mysqli_query($this->dbConnect, $sqlQuery); 
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        return $row;
    } 
    public function getInvoiceItems($invoiceId){
        $sqlQuery = "
            SELECT * FROM ".$this->invoiceOrderItemTable." 
            WHERE order_id = '$invoiceId'";
        return  $this->getData($sqlQuery); 
    }
 
 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);
        }
    }

Delete an Invoice

Let’s create a delete invoice functionality using jquery ajax, the user will click the delete icon from the listing, the confirmation box will display, once the user confirms the action, the invoice ll delete from the database.

PHP method To Delete an invoice

Let’s add the below code into the ajax_admin.php file:

<?php
session_start();
include 'invoice/action.php';
$invoice = new Invoice();
if($_POST['action'] == 'delete_invoice' && $_POST['id']) {
 $invoice->deleteInvoice($_POST['id']); 
 $jsonResponse = array(
  "status" => 1 
 );
 echo json_encode($jsonResponse); 
}

Action method to delete Invoice

Let’s create two methods into action.php, that’ll delete order and its details from mysql database table:

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;
    }

Print and Download an Invoice

Let’s create a print and download invoice functionality, I am using PHP library Dompdf to create PDF from HTML.

In the print.php file, we will add functionality to create invoice PDFs so that users may print or download invoices. We’ll use the invoice methods getInvoice() and getInvoiceItems() to get invoice details from database tables.

Added below code into the print.php file:

<?php
session_start();
include 'action.php';
$invoice = new Invoice();
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 $_SERVER["DOCUMENT_ROOT"].'/invoice-management/libs/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));
?>   

View Comments

  • Thank you for this nice work.
    Question: What do you need to do if you want to display a logo at the top right or left side of the the printed invoice?

    • create image container and paste logo url as a src attribute, You can use bootstrap image container.

  • hi nice code, I would like to add button beside Add Item, copy previous invoice items, where on click previous invoice list will appear and on select, it should insert all items from previous selected invoice. user than can remove not required items or add additional items.

    can you refer to sample code for such requirement.

  • Nice work how about i will add a discount under the tax rate? can you tell me what code iwill use?

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

4 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

10 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

10 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

10 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

11 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

11 months ago

Categories