Como Construi un sistema de facturaci贸n con PHP y MySQL

Los sistemas馃槂 de gesti贸n de facturaci贸n o facturaci贸n son muy populares ya que ahora la mayor铆a de las transacciones se realizan en l铆nea.聽Ahora todos los vendedores y compradores necesitan un sistema de facturaci贸n para gestionar la facturaci贸n en l铆nea.聽Entonces, si est谩 buscando un sistema de facturaci贸n o facturaci贸n con PHP y MySQL, entonces est谩 en el lugar correcto.聽馃槂En este tutorial, aprender谩 c贸mo desarrollar un sistema de facturaci贸n y facturaci贸n utilizando PHP y MySQL.

Cubriremos este tutorial en pasos sencillos con demostraci贸n en vivo para desarrollar un sistema 馃槏completo de facturas para crear y editar facturas con la impresi贸n de facturas para convertirlas en formato PDF.聽Tambi茅n permitiremos descargar el c贸digo fuente completo de la demostraci贸n en vivo.

Como cubriremos este tutorial con un ejemplo en vivo para crear un sistema de facturaci贸n con PHP y MySQL, los siguientes archivos principales para este ejemplo son los siguientes.

  • index.php
  • invoice_list.php
  • create_invoice.php
  • edit_invoice.php
  • action.php
  • factura.js
  • Factura.php

Paso 1: Crear las tablas de la base de datos MySQL
Primero, crearemos la tabla invoice_user para almacenar los detalles de inicio de sesi贸n del usuario para permitir que el usuario que ha iniciado sesi贸n administre las facturas.

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;

Crearemos la tabla invoice_order para almacenar los detalles de la factura.

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;

Tambi茅n crearemos la tabla invoice_order_item para almacenar los detalles de los art铆culos de la factura.

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;

Paso 2: Implementar el inicio de sesi贸n del usuario
Primero, crearemos la funcionalidad de inicio de sesi贸n del usuario para proporcionar acceso a la gesti贸n de facturas a los usuarios registrados. Vamos a crear el formulario de inicio de sesi贸n en 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>

Manejaremos la funcionalidad de inicio de sesi贸n en el formulario de inicio de sesi贸n mediante el m茅todo 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!";
}
}
?>

Paso 3: Mostrar la lista de facturas
Ahora mostraremos la lista de facturas del usuario en el archivo invoice_list.php . Llamaremos al m茅todo de factura getInvoiceList () para obtener la lista registrada en la lista de facturas del usuario.

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

Paso 4: Implementar la Factura Crear
ahora en create_invoice.php , implementaremos la funcionalidad para crear la factura. Crearemos un formulario de factura con los campos obligatorios para guardar los detalles de la factura con los art铆culos y los totales.

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

Guardaremos los detalles de la factura utilizando el m茅todo de facturaci贸n saveInvoice () .

<?php
include 'Invoice.php';
$invoice = new Invoice();
$invoice->saveInvoice($_POST);
?>

Paso 5: Implementar la Actualizaci贸n de Facturas
Ahora en edit_invoice.php , implementaremos la funcionalidad para editar la factura. Crearemos un formulario de factura con los campos obligatorios para guardar los detalles de edici贸n de facturas con art铆culos y totales.

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

Editaremos la factura guardada utilizando el m茅todo de facturaci贸n updateInvoice ()

<?php
include 'Invoice.php';
$invoice = new Invoice();
$invoice->updateInvoice($_POST);
?>

Paso 6: Implementar impresi贸n de facturas
ahora implementaremos la funcionalidad para crear PDF de facturas en el archivo print_invoice.php para permitir al usuario imprimir o descargar facturas. Obtendremos losdetalles de la factura de las tablas de la base de datos utilizando el m茅todo de factura getInvoice ()getInvoiceItems () . Luego usaremos la biblioteca PHP Dompdf para crear PDF desde 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));
?>

Paso 7: Implementar la eliminaci贸n de facturas Implementaremos la
funcionalidad de eliminaci贸n de facturas en invoice.js . Manejaremos la funcionalidad en el controlador deleteInvoice y haremos una solicitud de Ajax a action.php para eliminar la factura de la tabla de la base de datos.

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

En action.php , verificaremos la acci贸n de eliminaci贸n de facturas y la identificaci贸n de la factura para eliminar la factura usando el m茅todo de facturaci贸n deleteInvoice () y devolver la respuesta JSON.

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

Paso 8: Implementar el
cierre de sesi贸n del usuario Tambi茅n implementaremos la funcionalidad de cierre de sesi贸n del usuario pasando el cierre de sesi贸n de acci贸n a action.php

<?php
if($_GET['action'] == 'logout') {
session_unset();
session_destroy();
header("Location:index.php");
}
?>

Paso 9: Complete el m贸dulo de factura con el m茅todo
Crearemos la conexi贸n de la base de datos MySQL y todos los m茅todos en Invoice.php . Aqu铆 est谩 la lista completa de los m茅todos de facturaci贸n.

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

Puede ver la demostraci贸n en vivo desde el enlace Demo y puede descargar el script completo desde el enlace de descarga a continuaci贸n. 

Main Menu