How to save dynamically created table row data to database - javascript

This is my HTML and javascript script
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date" id="date" value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount" id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit" class="text-right" id="txtUnit" oninput="calculate()" value="1" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal" class="text-right" id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary" hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd" class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;" id="select">select</th>
<th style="width: 50px; text-align: center !important;">Sl.No</th>
<th style="width: 125px; text-align: center !important;">Date</th>
<th style="width: 175px; text-align: center !important;">Service</th>
<th style="width: 80px; text-align: center !important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal" oninput="addTotal();" id="txtGrandTotal" readonly/>
This is my javascript code
<div id="ta">
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td class='mar'><input type='checkbox' class='chk'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td class='date1' name='date'>"
+ date + "</td><td name='amount'>"
+ amount + "</td><td name='unit'>"
+ unit + "</td><td name='total' id='txtTot-"+lclCount+"'>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
</script>
<!-- <div class="page-break"></div> -->
</div>
<input type="submit" name="save" value="save">
and last here is my php code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$date = $_POST["date"];
$amount = $_POST["txtAmount"];
$unit = $_POST["txtUnit"];
$total = $_POST["txtTotal"];
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
?>
Here I want to save the that generate from dynamically created table data to the database but I am tried a lot but not able to save to the database getting an error like undefined index date amount etc. here I want generate id for every row that for automatically generated table row but not getting how to generate is there any other solution foe this guys. Thank in Advance.

Here's how you can do it, by using "arrays" on the inputs name, by defining the inputs name like arrays eg: "date" will be "date[]"
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date" value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]" id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right" id="txtUnit" oninput="calculate()" value="1" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right" id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary" hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd" class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;" id="select">select</th>
<th style="width: 50px; text-align: center !important;">Sl.No</th>
<th style="width: 125px; text-align: center !important;">Date</th>
<th style="width: 175px; text-align: center !important;">Service</th>
<th style="width: 80px; text-align: center !important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal" oninput="addTotal();" id="txtGrandTotal" readonly/>
And on the server side, you iterate on the received arrays:
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>

Related

how to find cell & get cell value in html Dynamic table use for jquery or javascript?

I have dynamic table. i am try to get cell value use jquery "closest & find" option. but not response it.
this is html code part.
<td>
<div id="ctrl-qun-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-qun-row<?php echo $row; ?>" value="<?php echo $this->set_field_value('qun',"", $row); ?>" type="number" placeholder="Enter Qun" step="0.1" required="" name="row<?php echo $row ?>[qun]" class="form-control " />
</div>
</td>
i am try to script used keyup event.
$('#ctrl-qun').on('keyup', function(){
var rowtoatal =0;
var $row =$(this).closest("td");
var qun2 =parseFloat($row.find('.qun').val());
alert($("#qun2").val()); //remove after testing
});
full code https://pastebin.com/9ZKRNH3b
You need to get the closest tr where the quantity is change and using this tr we can get value for unit price and add total to sub total column.
Demo Code (Added dummy data in value attribute of inputs):
//on change of qty
$('.qtn').on('change keyup ', function() {
//getting closest tr
var elem = $(this).closest(".input-row");
//get qty value
var qty = parseFloat($(this).val());
var rowtoatal = 0;
//get unit price value
var $row = parseFloat(elem.find("td input.unit").val());
rowtoatal = qty * $row;
console.log(qty + " * " + $row + " = " + rowtoatal)
//adding total to sub_total
elem.find("td input.sub_total").val(rowtoatal)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<table class="table table-striped table-sm" data-maxrow="100" data-minrow="1">
<thead>
<tr>
<th class="bg-light"><label for="product">Product</label></th>
<th class="bg-light"><label for="qun">Qun</label></th>
<th class="bg-light"><label for="unite_price">Unite Price</label></th>
<th class="bg-light"><label for="sub_total">Sub Total</label></th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="input-row">
<td>
<div id="ctrl-product-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-product-row<?php echo $row; ?>" value="Abcd" type="text" placeholder="Enter Product" required="" name="row<?php echo $row ?>[product]" class="form-control " />
</div>
</td>
<td data="abc">
<div id="ctrl-qun-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-qun-row<?php echo $row; ?>" value="1" type="number" placeholder="Enter Qun" step="0.1" required="" name="row<?php echo $row ?>[qun]" class="form-control qtn" />
<!--addded qtn class-->
</div>
</td>
<td>
<div id="ctrl-unite_price-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-unite_price-row<?php echo $row; ?>" value="75" type="number" placeholder="Enter Unite Price" step="0.1" required="" name="row<?php echo $row ?>[unite_price]" class="form-control unit" />
<!--added unit class-->
</div>
</td>
<td>
<div id="ctrl-sub_total-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-sub_total-row<?php echo $row; ?>" value="75" type="number" placeholder="Enter Sub Total" step="0.1" required="" name="row<?php echo $row ?>[sub_total]" class="form-control sub_total" />
<!-- added sub_total class-->
</div>
</td>
<th class="text-center">
<button type="button" class="close btn-remove-table-row">×</button>
</th>
</tr>
<tr class="input-row">
<td>
<div id="ctrl-product-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-product-row<?php echo $row; ?>" value="Abc" type="text" placeholder="Enter Product" required="" name="row<?php echo $row ?>[product]" class="form-control " />
</div>
</td>
<td>
<div id="ctrl-qun-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-qun-row<?php echo $row; ?>" value="1" type="number" placeholder="Enter Qun" step="0.1" required="" name="row<?php echo $row ?>[qun]" class="form-control qtn" />
</div>
</td>
<td>
<div id="ctrl-unite_price-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-unite_price-row<?php echo $row; ?>" value="20" type="number" placeholder="Enter Unite Price" step="0.1" required="" name="row<?php echo $row ?>[unite_price]" class="form-control unit" />
</div>
</td>
<td>
<div id="ctrl-sub_total-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-sub_total-row<?php echo $row; ?>" value="10" type="number" placeholder="Enter Sub Total" step="0.1" required="" name="row<?php echo $row ?>[sub_total]" class="form-control sub_total" />
</div>
</td>
<th class="text-center">
<button type="button" class="close btn-remove-table-row">×</button>
</th>
</tr>
</tbody>
</table>

Enable Edit button if new record exists

I created a modal where I can insert new client record and edit the same record. But in relation to the edit button, I wanted it to be active only when there was a new record in the database and until the end of the day it was registered.
<a type="button" name="editar" id="'.$row["IdCliente"].'" data-toggle="modal" href="#add_data_Modal" class="btn btn-primary edit_data">Update</a>
I'm trying this way:
if(isset($_POST["employee_id3"]))
{
$output = '';
$query = "SELECT * FROM centrodb.PsicUtentes LEFT OUTER JOIN centrodb.PsicUtentesConsulta ON centrodb.PsicUtentesConsulta.CodigoUtente2 = centrodb.PsicUtentes.CodigoUtente WHERE centrodb.PsicUtentes.Id = '".$_POST["employee_id3"]."' ORDER BY IdConsulta DESC ";
$result = mysqli_query($conn, $query);
$output;
while($row = mysqli_fetch_array($result))
{
$dataAtual = DATE('Y-m-d');
$disabled = "";
if(DATE($row['Data2'])!=$dataAtual){
$disabled = "disabled";
}
$output .= '
<h4 class="modal-title">Histórico de Consultas</h4>
<div>
<button type="button" class="exibir botao" href="#" aria-hidden="true">+</button>
<button type="button" href="#" class="ocultar botao" aria-hidden="true">-</button>
</div>
<div class="conteudo">
<form method="post" id="insert_form6">
<div style="float:right">
<a type="button" name="edit3" id="'.$row["Id"].','.$row["IdConsulta"].'" data-toggle="modal" href="#add_data_Modal3" class="btn btn-primary edit_data3" "$disabled">Editar</a>
</div>
<br/>
<br/>
<br/>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<input type="Hidden" id="IdConsulta1" name="IdConsulta" class="form-control" value="'.$row["IdConsulta"].'" style="width:150px;" readonly="true" />
</td>
<td>
<label>Data Consulta</label>
<input type="text" id="Data23" name="Data2" class="form-control" value="'.$row["Data2"].'" style="width:150px;" readonly="true" />
</td>
<td>
<label>Código Utente</label>
<input type="number" id="CodigoUtente5" name="CodigoUtente" value="'.$row["CodigoUtente"].'" class="form-control" style="width:100px;" readonly="true"/>
</td>
<td>
<label>Nome Utente</label>
<input type="text" id="Nome5" name="Nome" value="'.$row["Nome"].'" class="form-control" style="width:400px;" readonly="true"/>
</td>
<td>
<label>Data Nascimento</label>
<input type="date" id="DataNasc5" name="DataNasc" value="'.$row["DataNasc"].'" class="form-control" style="width:150px;" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>Data Admissao</label>
<input type="date" id="DataAdmissao5" name="DataAdmissao" value="'.$row["DataAdmissao"].'" class="form-control" style="width:150px;" readonly="true"/>
</td>
<td>
<label>Valência</label>
<input type="text" id="ValenciasDescricao5" name="ValenciasDescricao" value="'.$row["ValenciasDescricao"].'" class="form-control" style="width:200px;" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>Observação</label>
</p><textarea rows="6" cols="130" readonly="true">'.$row["Descricao"].'</textarea>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>O Psicologo/a</label>
<input type="text" id="Colaborador2" name="Colaborador2" class="form-control" style="width:150px;" value="'.$row["Colaborador2"].'" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
</form>
</div>
';
}
$output;
echo $output;
}
<script>
$(document).ready(function(){
$(document).on('click', '.edit_data3', function(){
var employee_id3 = $(this).attr("Id");
$.ajax({
url:"./fetch2",
method:"POST",
data:{employee_id3:employee_id3},
dataType:"json",
success:function(data){
$('#IdConsulta').val(data.IdConsulta);
$('#Data22').val(data.Data2);
$('#CodigoUtente6').val(data.CodigoUtente2);
$('#Descricao1').val(data.Descricao);
$('#Colaborador2').val(data.Colaborador2);
$('#employee_id3').val(data.Id);
$('#insert3').val("Gravar");
$('#add_data_Modal3').modal('show');
}
});
});
$('#insert_form7').on("submit", function(event){
event.preventDefault();
if($('#CodigoUtente6').val() == "")
{
alert("Código Utente é necessário");
}
else if($('#Descricao1').val() == "")
{
alert("Observação é necessária");
}
else
{
$.ajax({
url:".conexao9",
method:"POST",
data:$('#insert_form7').serialize()
,
beforeSend:function(){
$('#insert3').val("Inserting");
},
success:function(data){
$('#insert_form7')[0].reset();
$('#add_data_Modal3').modal('hide');
$('#employee_table').html(data);
location.reload("add_data_Modal3");
}
});
}
});
});
</script>
I created a variable with the current date that compares with the date of the record. I created an empty disabled variable. There I put this disabled variable in the link. If the date is different than the current date you put the disabled variable filled.The problem is that the button stays in the same asset.
Firstly your code is vulnerable to sql injection attacks and you should use prepared statements.
Then you have some syntax errors on your code.
The lines $output; are useless, delete them.
Change "$disabled" to '.$disabled'.
and put ?> before your <script> tag.

Get data-price attribute from dynamically added row and put inside the input box

how to get data-price inside the text box using select in php html and sql?
i tried this so far. what im trying to do is, when i change the selection box, the input box beside should change base on the value of data-price.
been trying this for a week.
e.g
select debit
local treasury 100
<script>
$(document).ready(function(){
var i=1;
var chart_add = '<tr id="row_chart'+i+'"><td><select name="chart_of_account[]" class="selectpicker" data-live-search="true"><option style="width: 400px;">--Select Chart of Account--</option><?php $chart=mysqli_query($conn,"Select acoount_no,account_title from chart_of_account"); while($row=mysqli_fetch_assoc($chart)){$account_no = $row["acoount_no"]; $account_title = $row["account_title"];?><option value="<?php echo $account_no; ?>" style="width: 400px;"><?php echo $account_no ." | ". $account_title; ?></option><?php }?></select></td><td><input type="text" name="chart_debit[]" class="form-control chart_debit" id="chart_debit"onchange="chart_change_debit()"></td><td><input type="text" name="chart_credit[]" class="form-control chart_credit" id="chart_credit" onchange="chart_change_credit()"></td><td><button type="button" name="remove_chart" id="'+i+'" class="btn btn-danger remove_chart">X</button></td></tr>';
$('#add').click(function(){
i++;
$('#dynamic_field').append(chart_add);
$('.selectpicker').selectpicker('render');
$('.chart_debit').val($('select[name="chart_of_account"] option:selected').data('price'));
});
$(document).on('click', '.remove_chart', function(){
var button_id = $(this).attr("id");
$('#row_chart'+button_id+'').remove();
});
});
</script>
<form method = "POST" name="add_name" id="add_name">
<div class="row">
<div class="col-md-12">
<!-- chart of account -->
<div class="row">
<div class="col-md-12">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Chart of Account</h3>
</div>
<div class="box-body">
<table class="table table-bordered" id="dynamic_field">
<tr>
<th rowspan="2">Chart of Account</th>
<th>Debit</th>
<th>Credit</th>
<th rowspan="2"><button type="button" name="add" id="add" class="btn btn-success">Add More</button></th>
</tr>
<tr>
<th>
<input type="text" name="chart_debit_sum" class="form-control chart_debit_sum" id="chart_debit_sum" readonly>
</th>
<th>
<input type="text" name="chart_credit_sum" class="form-control chart_credit_sum" id="chart_credit_sum" readonly>
</th>
</tr>
<tr>
<td>
<select name="chart_of_account[]" class="selectpicker" data-live-search="true">
<option style="width: 400px;">--Select Chart of Account--</option>
<?php
$chart = mysqli_query($conn,"Select acoount_no,account_title from chart_of_account");
while($row = mysqli_fetch_assoc($chart)){
$account_no = $row['acoount_no'];
$account_title = $row['account_title'];
$amount = $row['test_amount'];
?>
<option value = "<?php echo $account_no; ?>" style="width: 400px;" data-price = "<?php echo $amount; ?>">
<?php echo $account_no . " | " .$account_title; ?>
</option>
<?php } ?>
</select>
</td>
<td>
<input type="text" name="chart_debit[]" class="form-control chart_debit" id="chart_debit" onchange="chart_change_debit()">
</td>
<td>
<input type="text" name="chart_credit[]" class="form-control chart_credit" id="chart_credit" onchange="chart_change_credit()">
</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- chart of account -->
</div>
<!-- chart and sub-->
</div>
</form>
sample screenshot

How to save Dynamically Generated table rows to database

This is My HTML Code
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date"
value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]"
id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right"
id="txtUnit" oninput="calculate()" value="1" onkeypress="return
isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right"
id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary"
hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd"
class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;"
id="select">select</th>
<th style="width: 50px; text-align: center
!important;">Sl.No</th>
<th style="width: 125px; text-align: center
!important;">Date</th>
<th style="width: 175px; text-align: center
!important;">Service</th>
<th style="width: 80px; text-align: center
!important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal"
oninput="addTotal();" id="txtGrandTotal" readonly/>
</form>
This is My PHP code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount,
backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>
This is MY JAVASCRIPT CODE
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td><input type='checkbox'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td>"
+ date + "</td><td>"
+ amount + "</td><td>"
+ unit + "</td><td>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
Here I want to save whatever is generated from dynamically created table data to the database. I tried a lot but unable to do so. Am getting an error saying undefined index date amount etc. Here I want to generate id for every automatically generated table row but unable to figure out how to do so.
Is there any other solution for this ?
Thank in Advance.
Okay....
In my code I'm created a div with class data in which I put four inputs date,amount,unit and total.
I add plus and minus buttons in last for add/remove row.
by clicking plus button clone of previous row appear in last
On submit data of all input will be send to the submit URL.
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"])){
$value = '';
for ($i=0;$i<count($_POST['date']);$i++) {
$value .= '("'.$_POST["date"][$i].'","'.$_POST["amount"][$i].'","'.$_POST["unit"][$i].'","'.$_POST["total"][$i].'"),';
}
$value = rtrim($value,",");
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ".$value;
$result = mysqli_query($conn, $sql);
}
echo '
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><br />
<div class="container">
<h2>Vertical (basic) form</h2>
<form action="/action_page.php">
<div class="row data" divid="1">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Date</span>
<input type="text" class="form-control date" value="'.date('Y/M/d').'" id="date-1" placeholder="Enter date" name="date[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Amount</span>
<input type="text" class="form-control amount" data-id="1" value="0" id="amount-1" placeholder="Enter Amount" name="amount[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Unit</span>
<input type="text" class="form-control unit" data-id="1" id="unit-1" value="0" placeholder="Enter Unit" name="unit[0]" />
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<span class="input-group-addon">Total</span>
<input type="text" class="form-control total" id="total-1" readonly="readonly" name="total[0]" />
</div>
</div>
<div class="col-md-1">
<button class="btn btn-success btn-block plus" type="button" id="p-1">+</button>
<button class="btn btn-danger btn-block minus hide" type="button" id="m-1">-</button>
</div>
</div>
<div class="row"><div class="col-md-3"> </div></div>
<div class="row">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Grand Total</span>
<input type="text" class="form-control" value="0" id="g-total" readonly="readonly" name="g_total" />
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-default" name="save">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>';
?>
<script type="text/javascript">
$(document).on('change','.unit,.amount',function(e) {
id = parseInt($(this).attr("id").replace("unit-", "").replace("amount-",""));
get_total(id);
});
function get_total(id){
unit_d = parseInt($('#unit-'+id).val());
amount = parseInt($('#amount-'+id).val());
total = Math.ceil(amount*unit_d);
$('#total-'+id).val(total);
var g_total = 0;
jQuery('.total').each(function(){
g_total = g_total+parseInt($(this).val());
});
$('#g-total').val(g_total);
}
/****************************JS for add new row****************************/
$(document).on('click','.plus',function(e) {
var thisRow = $('.data').last(".data");
var newid = parseInt(thisRow.attr('divid'))+1;
var cid = parseInt(thisRow.attr('divid'));
var date = $('#date-'+cid).val();
var amount = $('#amount-'+cid).val();
var n_unit = $('#unit-'+cid).val();
var total = $('#total-'+cid).val();
if(date=="") $('#date-'+cid).addClass('error'); else $('#date-'+cid).removeClass('error');
if(amount=="") $('#amount-'+cid).addClass('error'); else $('#amount-'+cid).removeClass('error');
if(n_unit=="") $('#unit-'+cid).addClass('error'); else $('#unit-'+cid).removeClass('error');
if(total=="") $('#total-'+cid).addClass('error'); else $('#total-'+cid).removeClass('error');
if((date!="")&&(amount!="")&&(n_unit!="")&&(total!="")){
$('#date-'+cid+',#amount-'+cid+',#unit-'+cid).attr('readonly','readonly');
newRow = thisRow.clone(true).insertAfter(thisRow).find('input').val('').end().
find('.date').each(function(){
$(this).attr('id', 'date-'+newid);
$(this).attr('name','date['+(newid-1)+']');
$(this).val($('#date-'+cid).val());
$(this).removeAttr('readonly');
}).end().find('.amount').each(function(){
$(this).attr('id', 'amount-'+newid);
$(this).attr('name','amount['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.unit').each(function(){
$(this).attr('id', 'unit-'+newid);
$(this).attr('name','unit['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.total').each(function(){
$(this).attr('id', 'total-'+newid);
$(this).attr('name','total['+(newid-1)+']');
$(this).val(0);
}).end().find('.plus').each(function(){
$(this).attr('id', 'p-'+newid);
$(this).attr('data-id', newid);
}).end().find('.minus').each(function(){
$(this).attr('id', 'm-'+newid);
}).end();
thisRow.next('.data').attr("divid",newid).addClass('child');
$('.minus').removeClass('hide');
$('.plus').addClass('hide');
$('#m-'+newid).addClass('hide');
$('#p-'+newid).removeClass('hide');
}
});
/****************************JS for add new row****************************/
/****************************JS for delete row****************************/
$('.minus').click(function(e) {
$(this).closest('.data').remove();
});
/****************************JS for delete row****************************/ </script>

How to Create a Shopping Cart using Session in PHP

I'm having trouble creating a shopping cart. How do I make the output so that when I click the add cart button on my products table, it will appear on the cart?
//Product List
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$product_quantity = $row['quantity'];
$product_price = $row['sell_price'];
?>
<tr>
<td class="text-center"><?php echo $product_id; ?></td>
<td><?php echo $product_name; ?></td>
<td><?php echo $product_price; ?></td>
<td><?php echo $product_quantity; ?></td>
<td class="text-center">
<div class="btn-group">
<a href="add_sales.php?action=add&product_id=<?php echo $product_id; ?>" class="btn btn-xs btn-info" data-toggle="tooltip" title="Select">
<span class="fa fa-shopping-cart"></span>
</a>
</div>
</td>
</tr>
<?php } ?>
Item Details Panel
if (isset($_GET['product_id'])) {
$prod_id = $_GET['product_id'];
$selectProd = "SELECT * FROM products WHERE product_id = $prod_id";
$execProd = mysqli_query($connection, $selectProd);
while ($row = mysqli_fetch_array($execProd)) {
$prod_name = $row['product_name'];
$prod_price = $row['sell_price'];
$quantity = $row['quantity'];
?>
<div class="panel-body">
<div class="col-md-2">
<div class="form-group">
<label for="">Item ID</label>
<input type="text" class="form-control" value="<?php echo $prod_id; ?>" readonly>
</div>
</div>
<div class="col-md-7">
<div class="form-group">
<label for="">Item Name</label>
<input type="text" class="form-control" value="<?php echo $prod_name ?>" readonly>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Unit Price</label>
<input type="text" class="form-control" value="<?php echo $prod_price; ?>" readonly id="unitPrice">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="">Available Qty</label>
<input type="text" class="form-control" value="<?php echo $quantity ?>" readonly>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Sale Qty</label>
<input type="number" class="form-control" id="saleQty" name="saleQty">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="">Total Amount</label>
<input type="text" class="form-control" id="totalSale" name="saleTotal" readonly>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="submit" value="Add to Cart" class="btn btn-info form-control" formnovalidate>
</div>
</div>
Cart
<!-- Start of Customer's Cart -->
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<strong>
<span class="fa fa-shopping-cart"></span>
<span>Customer's Cart</span>
</strong>
</div>
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Quantity</th>
<th>Product Amount</th>
<th>Total Amount</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- End of Customer Cart -->
Ordering Page Flow (GIF)
None of your input element have name attributes so (I think) when you submit the form, the URL query parameters (if the form has GET method) or the request body parameters (POST method) won't be available and you can't "catch" the act of someone submitting the order. If you add them and handle the form submission (say by ifing on a isset($_POST['order']) you can INSERT the order into the DB and render the cart from the DB table. Also look into http://php.net/manual/en/mysqli.prepare.php to avoid SQL injection.

Categories