Multiple Inline Insert into Mysql using Ajax JQuery in PHP - php

I am new in php. I trying to know Multiple Inline Insert into Mysql using Ajax JQuery in PHP.
Then I follow this tutorial on "webslesson". My all codes and database are Ok as like as webslesson web tutorial . But my save button doesn't work and don't send any data in my database and also not shown any error....
index.php
<!DOCTYPE html>
<html>
<head>
<title>Multiple Inline Insert into Mysql using Ajax JQuery in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<br />
<h2 align="center">Multiple Inline Insert into Mysql using Ajax JQuery in PHP</h2>
<br />
<div class="table-responsive">
<table class="table table-bordered" id="crud_table">
<tr>
<th width="30%">Item Name</th>
<th width="10%">Item Code</th>
<th width="45%">Description</th>
<th width="10%">Price</th>
<th width="5%"></th>
</tr>
<tr>
<td contenteditable="true" class="item_name"></td>
<td contenteditable="true" class="item_code"></td>
<td contenteditable="true" class="item_desc"></td>
<td contenteditable="true" class="item_price"></td>
<td></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="center">
<button type="button" name="save" id="save" class="btn btn-info">Save</button>
</div>
<br />
<div id="inserted_item_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='item_name'></td>";
html_code += "<td contenteditable='true' class='item_code'></td>";
html_code += "<td contenteditable='true' class='item_desc'></td>";
html_code += "<td contenteditable='true' class='item_price' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var item_name = [];
var item_code = [];
var item_desc = [];
var item_price = [];
$('.item_name').each(function(){
item_name.push($(this).text());
});
$('.item_code').each(function(){
item_code.push($(this).text());
});
$('.item_desc').each(function(){
item_desc.push($(this).text());
});
$('.item_price').each(function(){
item_price.push($(this).text());
});
$.ajax({
url:"insert.php",
method:"POST",
data:{item_name:item_name, item_code:item_code, item_desc:item_desc, item_price:item_price},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
fetch_item_data();
}
});
});
function fetch_item_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#inserted_item_data').html(data);
}
})
}
fetch_item_data();
});
</script>
insert.php
<?php
//insert.php
$connect = mysqli_connect("127.0.0.1", "root", "", "testing4");
if(isset($_POST["item_name"]))
{
$item_name = $_POST["item_name"];
$item_code = $_POST["item_code"];
$item_desc = $_POST["item_desc"];
$item_price = $_POST["item_price"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
$item_desc_clean = mysqli_real_escape_string($connect, $item_desc[$count]);
$item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_desc_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO item(item_name, item_code, item_description, item_price)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_desc_clean.'", "'.$item_price_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}
else
{
echo 'All Fields are Required';
}
}
?>
fetch.php
<?php
//fetch.php
$connect = mysqli_connect("127.0.0.1", "root", "", "testing4");
$output = '';
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);
$output = '
<br />
<h3 align="center">Item Data</h3>
<table class="table table-bordered table-striped">
<tr>
<th width="30%">Item Name</th>
<th width="10%">Item Code</th>
<th width="50%">Description</th>
<th width="10%">Price</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["item_name"].'</td>
<td>'.$row["item_code"].'</td>
<td>'.$row["item_description"].'</td>
<td>'.$row["item_price"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
?>
This is my database......
item.sql
--
-- Database: `testing4`
- -
-- --------------------------------------------------------
--
-- Table structure for table `item`
--
CREATE TABLE `item` (
`item_id` int(11) NOT NULL,
`item_name` varchar(250) NOT NULL,
`item_code` varchar(250) NOT NULL,
`item_description` text NOT NULL,
`item_price` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Related

delete multiple row in php table data using cheque box

I have this script where the delete function is not working. The row gets removed from the table as the same was called for.. but the same re-appears as the same is not been removed from the actual database..
My table's :
This is given for the delete button:
<th >Follow Up Date</th>
<th >Name SM</th>
<th >Entered Date</th>
<th >Edit</ht>
<th ><button type="button" name="delete_all" id="delete_all" class="btn btn-danger btn-xs">Delete</button></th>
The second where the there is check box:
<td><?php echo $row["NameSM"]; ?></td>
<td><?php echo $row["EnteredDate"]; ?></td>
<td><input type="button" name="edit" value="Edit" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
<td><input type="checkbox" class="delete_checkbox" value="'.$row["id"].'" /></td>
The Delete Script :
<style>
.removeRow
{
background-color: #FF0000;
color:#FFFFFF;
}
</style>
<script>
$(document).ready(function(){
$('.delete_checkbox').click(function(){
if($(this).is(':checked'))
{
$(this).closest('tr').addClass('removeRow');
}
else
{
$(this).closest('tr').removeClass('removeRow');
}
});
$('#delete_all').click(function(){
var checkbox = $('.delete_checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"delete.php",
method:"POST",
data:{checkbox_value:checkbox_value},
success:function()
{
$('.removeRow').fadeOut(1500);
}
});
}
else
{
alert("Select atleast one records");
}
});
});
</script>
The delete.php page :
<?php
//database_connection.php = $connect = new PDO("mysql:host=localhost;dbname=u771775069_data", "root", "");
include('database_connection.php');
if(isset($_POST["checkbox_value"]))
{
for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
{
$query = "DELETE FROM data WHERE id = '".$_POST['checkbox_value'][$count]."'";
$statement = $connect->prepare($query);
$statement->execute();
}
}
?>

Using datepicker and saving values from form to database

I have an editable input box that saves values to the database and it's working perfectly.
Now I wanted to try adding a datepicker inside that input box so what I did was:
<td contenteditable="true" class="date"><input type="date"></td>
Now when I hit send, I'm getting "All fields are required". Am I doing it wrong?
Here's the whole code for your reference:
<!DOCTYPE html>
<html>
<head>
<title>PC Request Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Questrial" rel="stylesheet">
<style type="text/css">
body {
font-family: 'Questrial', sans-serif;
}
</style>
</head>
<body>
<br /><br />
<div class="container">
<img src="img/corelogo.png" width="250px; height: 110px;"></img>
<h4>PC Request</h4>
<div class="table-responsive">
<table class="table table-bordered" style="border-radius: 10px;" id="crud_table">
<tr>
<th width="30%">Requested By</th>
<th width="10%">Start Date</th>
<th width="10%">Employee Name</th>
<th width="10%">Position</th>
<th width="10%">Account</th>
<th width="10%">Platform</th>
<th width="45%">Processor</th>
<th width="10%">RAM</th>
<th width="10%">Monitor</th>
<th width="10%">Phone</th>
<th width="10%">Phone Type</th>
<th width="10%">Headset</th>
</tr>
<tr>
<td contenteditable="true" class="reqname"></td>
<td contenteditable="true" class="date"><input type="date"><td>
<td contenteditable="true" class="empname"></td>
<td contenteditable="true" class="position"></td>
<td contenteditable="true" class="account"></td>
<td contenteditable="true" class="platform"></td>
<td contenteditable="true" class="processor"></td>
<td contenteditable="true" class="ram"></td>
<td contenteditable="true" class="monitor"></td>
<td contenteditable="true" class="phone"></td>
<td contenteditable="true" class="phonetype"></td>
<td contenteditable="true" class="headset"></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="left">
<button type="button" name="save" id="save" class="btn btn-info">Send</button>
</div>
<br />
<div id="inserted_item_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='reqname'></td>";
html_code += "<td contenteditable='true' class='date'></td>";
html_code += "<td contenteditable='true' class='empname'></td>";
html_code += "<td contenteditable='true' class='position' ></td>";
html_code += "<td contenteditable='true' class='account' ></td>";
html_code += "<td contenteditable='true' class='platform' ></td>";
html_code += "<td contenteditable='true' class='processor' ></td>";
html_code += "<td contenteditable='true' class='ram' ></td>";
html_code += "<td contenteditable='true' class='monitor' ></td>";
html_code += "<td contenteditable='true' class='phone' ></td>";
html_code += "<td contenteditable='true' class='phonetype' ></td>";
html_code += "<td contenteditable='true' class='headset' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var reqname = [];
var date = [];
var empname = [];
var position = [];
var account = [];
var platform = [];
var processor = [];
var ram = [];
var monitor = [];
var phone = [];
var phonetype = [];
var headset = [];
$('.reqname').each(function(){
reqname.push($(this).text());
});
$('.date').each(function(){
date.push($(this).text());
});
$('.empname').each(function(){
empname.push($(this).text());
});
$('.position').each(function(){
position.push($(this).text());
});
$('.account').each(function(){
account.push($(this).text());
});
$('.platform').each(function(){
platform.push($(this).text());
});
$('.processor').each(function(){
processor.push($(this).text());
});
$('.ram').each(function(){
ram.push($(this).text());
});
$('.monitor').each(function(){
monitor.push($(this).text());
});
$('.phone').each(function(){
phone.push($(this).text());
});
$('.phonetype').each(function(){
phonetype.push($(this).text());
});
$('.headset').each(function(){
headset.push($(this).text());
});
$.ajax({
url:"insert-message.php",
method:"POST",
data:{reqname:reqname, date:date, empname:empname, position:position, account:account, platform:platform, processor:processor, ram:ram, monitor:monitor, phone:phone, phonetype:phonetype, headset:headset},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
fetch_item_data();
}
});
});
});
</script>
Insert values code:
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "pcrequesttest");
if(isset($_POST["reqname"]))
{
$reqname = $_POST["reqname"];
$date = $_POST["date"];
$empname = $_POST["empname"];
$position = $_POST["position"];
$account = $_POST["account"];
$platform = $_POST["platform"];
$processor = $_POST["processor"];
$ram = $_POST["ram"];
$monitor = $_POST["monitor"];
$phone = $_POST["phone"];
$phonetype = $_POST["phonetype"];
$headset = $_POST["headset"];
$query = '';
for($count = 0; $count<count($reqname); $count++)
{
$reqname_clean = mysqli_real_escape_string($connect, $reqname[$count]);
$date_clean = mysqli_real_escape_string($connect, $date[$count]);
$empname_clean = mysqli_real_escape_string($connect, $empname[$count]);
$position_clean = mysqli_real_escape_string($connect, $position[$count]);
$account_clean = mysqli_real_escape_string($connect, $account[$count]);
$platform_clean = mysqli_real_escape_string($connect, $platform[$count]);
$processor_clean = mysqli_real_escape_string($connect, $processor[$count]);
$ram_clean = mysqli_real_escape_string($connect, $ram[$count]);
$monitor_clean = mysqli_real_escape_string($connect, $monitor[$count]);
$phone_clean = mysqli_real_escape_string($connect, $phone[$count]);
$phonetype_clean = mysqli_real_escape_string($connect, $phonetype[$count]);
$headset_clean = mysqli_real_escape_string($connect, $headset[$count]);
if($reqname_clean != '' && $date_clean != '' && $empname_clean != '' && $position_clean != '' && $account_clean != '' && $platform_clean != '' && $processor_clean != '' && $ram_clean != '' && $monitor_clean != '' && $phone_clean != '' && $phonetype_clean != '' && $headset_clean != '')
{
$query .= '
INSERT INTO item(reqname, date, empname, position, account, platform, processor, ram, monitor, phone, phonetype, headset)
VALUES("'.$reqname_clean.'", "'.$date_clean.'", "'.$empname_clean.'", "'.$position_clean.'", "'.$account_clean.'", "'.$platform_clean.'", "'.$processor_clean.'", "'.$ram_clean.'", "'.$monitor_clean.'", "'.$phone_clean.'", "'.$phonetype_clean.'", "'.$headset_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Successfuly Sent!';
}
else
{
echo 'Error';
}
}
else
{
echo 'All fields are required!';
}
}
?>
When you're collecting values from your page, you do this:
$('.date').each(function(){
date.push($(this).text());
});
This is working for all of your contenteditable elements, for which their "value" is their text content. But you've now changed your markup here:
<td contenteditable="true" class="date"><input type="date"></td>
You're no longer editing the content of that td, but instead have an input within it. First, remove contenteditable since you're not using it anymore:
<td class="date"><input type="date"></td>
Then in your JavaScript code, instead of looking for the text content of the <td>, look for the value of the <input> therein. Perhaps something like this:
$('.date').each(function(){
date.push($(this).find('input').val());
});
You could change this up in a number of ways, such as moving the class to the <input> and getting the value irectly from that in your .each() loop. But the concept is still the same. You're no longer looking for the text of your <td>, you're now looking for the value of your <input>.

Trying to display live table which is editable using ajax and php

I have four different files
index.php
select.php
insert.php
edit.php
delete.php
In my backend I have created a database named 'ecc'
Database 'ecc' has atable named 'task'
The table task has following fields
id, name, category, cost
Datatype for id set to int and index as primary also id field is on auto increment
My Issue:My code is only displaying 'Live Table Data'.
It would be grate if someone rewrite it or suggest some changes.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var name = $('#name').text();
var category = $('#category').text();
var cost = $('#cost').text();
if(name == '')
{
alert("Enter Service Name");
return false;
}
if(category == '')
{
alert("Enter Category of Service");
return false;
}
if(cost == '')
{
alert("Enter cost");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{name:name, category:category, cost:cost},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.category', function(){
var id = $(this).data("id2");
var category = $(this).text();
edit_data(id,category, "category");
$(document).on('blur', '.cost', function(){
var id = $(this).data("id3");
var category = $(this).text();
edit_data(id,cost, "cost");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id4");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$output = '';
$sql = "SELECT * FROM task ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
<td class="cost" data-id3="'.$row["id"].'" contenteditable>'.$row["cost"].'</td>
<td><button type="button" name="delete_btn" data-id4="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="name" contenteditable></td>
<td id="category" contenteditable></td>
<td id="cost" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$sql = "INSERT INTO tbl_sample(name, category, cost) VALUES('".$_POST["name"]."', '".$_POST["category"]."', '".$_POST["cost"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
}
?>
edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$id = $_POST["id"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
$sql = "UPDATE task SET ".$column_name."='".$text."' WHERE id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
delete.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$sql = "DELETE FROM task WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
you can use data tables for this, no need of all this
https://editor.datatables.net/examples/inline-editing/simple
check this, data tables provide libraries for this

How do I add (sum of numbers) within a data-table in ajax even if a new row is added with jquery

I'm trying to make an addition (or subtraction if needed) to a php page with ajax.
What this code is supposed to do is add all the prices up and give me the correct sum with the live-edit-table.
if a user changes the value of price $price_total should change acordingly.
Even if a new row is added it should still give the new sum (displayed in $price_total and $final_price_total) with the new row included.
I have been trying to figure out how to do this but I can't figure out how.
$price_total and $final_price_total do not get saved into a database
this is the code that I have so far:
index.php
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data(){
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
fetch_data();
function edit_data(id, text, column_name){
$.ajax({
url:"edit.php",
method:"POST",
data:{
id:id,
text:text,
column_name:column_name
},
dataType:"text",
success:function(data){
/*alert(data);*/
}
});
}
$(document).on('click', '#btn_add', function(){
/* this function would also add the prices to the table*/
var price = $('#price').text();
var final_price = $('#final_price').text();
if(price == ''){
alert("Enter Price");
return false;
}
if(final_price == ''){
alert("Enter Final Price");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{price:price, final_price:final_price},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
})
});
$(document).on('blur', '.price', function(){
var id = $(this).data("id1");
var price = $(this).text();
edit_data(id, price, "price");
/*I'm trying so that I can add the new input price with the old total to give the exact value*/
$total = parseFloat( price ) + parseFloat( $('#price_total').value );
$('#price_total').value = formatDecimal(total);
});
$(document).on('blur', '.final_price', function(){
var id = $(this).data("id2");
var final_price = $(this).text();
edit_data(id, final_price, "final_price");
});
});
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$output = '';
$sql = "SELECT * FROM tbl_sample ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Price</th>
<th width="40%">Final Price</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0){
$final_price_total = 0;
$price_total = 0;
while($row = mysqli_fetch_array($result)){
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="price" data-id1="'.$row["id"].'" contenteditable>'.$row["price"].'</td>
<td class="final_price" data-id2="'.$row["id"].'" contenteditable>'.$row["final_price"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
$final_price_total += $row["final_price"];
$price_total += $row["price"];
}
$output .= '
<tr>
<td></td>
<td class="price_total" id="price_total" name="price_total" value="'.$price_total.'" contenteditable>'.$price_total.'</td>
<td class="final_price_total" id="final_price_total" name="final_price_total" value="'.$final_price_total.'" contenteditable>'.$final_price_total.'</td>
<td></td>
</tr>
';
$output .= '
<tr>
<td></td>
<td id="price" contenteditable></td>
<td id="final_price" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
From the little discussion in the question comments, I've managed to spot this variable typo:
$total = parseFloat( price ) + parseFloat( $('#price_total').value );
$('#price_total').value = formatDecimal(total);
On the second line you are using total instead of $total.
If you check your browser's error console, you will see an error about undeclared variable total.
Edit: after further discussion, you wanted to know how to loop over the table in JavaScript and add up the total. Try this:
var newTotal = 0.0;
$('.price').each(function() {
newTotal += parseFloat($(this).text());
});
If you do this on your edit finding, you can then use the newTotal variable in the final_price field in place of where you are using the $total variable.

AJAX live insert delete search, shows items 2 times

When i insert an item it is shown on the list 2 times, but on mysql table it is registered just one time. It started when i started using sessions. Thank you in advance.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Lista articulos prestados</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var Articulo = $('#Articulo').text();
var fecha = $('#fecha').text();
var emailpresta = $('#emailpresta').text();
var emailrecibe = $('#emailrecibe').text();
if(Articulo == '')
{
alert("Ingresa Articulo");
return false;
}
if(fecha == '')
{
alert("Ingresa Fecha");
return false;
}
if(emailpresta == '')
{
alert("Ingresa tu email");
return false;
}
if(emailrecibe == '')
{
alert("Ingresa email tercero");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{Articulo:Articulo, fecha:fecha, emailpresta:emailpresta, emailrecibe:emailrecibe },
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
session_start();
$check_usuario = $_SESSION['email'];
$connect = mysqli_connect("######", "######", "", "############");
$output = '';
$sql = "SELECT * FROM articulos INNER JOIN usuarios WHERE emailpresta='".$check_usuario."'";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Articulo</th>
<th width="40%">Fecha(Formato: AAAA-MM-DD)</th>
<th width="40%">Email-presta</th>
<th width="40%">Email-recibe</th>
<th width="10%">Borrar</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="Articulo" data-id1="'.$row["id"].'" contenteditable>'.$row["Articulo"].'</td>
<td class="fecha" data-id2="'.$row["id"].'" contenteditable>'.$row["fecha"].'</td>
<td class="emailpresta" data-id2="'.$row["id"].'" contenteditable>'.$row["emailpresta"].'</td>
<td class="emailrecibe" data-id2="'.$row["id"].'" contenteditable>'.$row["emailrecibe"].'</td>
<td><button type="button" name="delete_btn" data- id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="Articulo" contenteditable></td>
<td id="fecha" contenteditable></td>
<td id="emailpresta" contenteditable></td>
<td id="emailrecibe" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td></td>
<td id="Articulo" contenteditable></td>
<td id="fecha" contenteditable></td>
<td id="emailpresta" contenteditable></td>
<td id="emailrecibe" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
insert.php
<?php
session_start();
$connect = mysqli_connect("############", "############", "", "############");
$sql = "INSERT INTO articulos(Articulo, fecha, emailpresta, emailrecibe) VALUES('".$_POST["Articulo"]."', '".$_POST["fecha"]."'
, '".$_POST["emailpresta"]."', '".$_POST["emailrecibe"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
}
?>
delete.php
<?php
session_start();
$connect = mysqli_connect("############", "############", "", "############");
$sql = "DELETE FROM articulos WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
The problem is likely with you MySQL query. What shows up on screen when you execute the following:
//session_start(); <-- do not start session
$email = '......'; <-- use an email from the DB with data available
$sql = "SELECT * FROM articulos INNER JOIN usuarios
WHERE emailpresta='$email'";
$connect = mysqli_connect(...);
$result = mysqli_query($connect,$sql);
$data = mysqli_fetch_all($result));
print_r($data);
Do you see duplicate rows? If so, you'll need to work on your SQL query. Specifically, you don't tell the database how to join the articulos and usarios tables. Instead of
SELECT * from articulos INNER JOIN usarios WHERE emailpresta='$email'
You probably need something like:
SELECT * from articulos INNER JOIN usarios ON articulos.userID=usarios.ID
WHERE usarios.emailpresta='$email'
Instead of articulos.userID and usarios.ID, use the fields in the two tables that match up. You can learn a bit about INNER JOIN here
Side note
I noticed that you plug $_SESSION['email'] directly into your DB query. If this is a value that you received from the user, you run a huge risk of SQL injection attack, a way for anyone to execute any query (including extracting, modifying or deleting your DB records) using specially crafted inputs. Look into using parameterized queries instead. Even if the contents of $_SESSION['email'] are safe, running raw queries is a risky habit anywhere you take input from the user.

Categories