dynamic table saving in db using checkboxes php mysql - javascript

I have the following table to be saved to the DB. the $varline is a counter, used to total up the row values.
<table id="table1" border="1">
<tbody>
<tr>
<th>First Name</th>
<th>id</th>
<th>Price</th>
<th>Qty</th>
<th>Select</th>
</tr>
<tr>
<td>A1</td>
<td><input type="text" value="$id" name='item[$varline][id]'></td>
<td><input type="text" value="$price" name='item[$varline][price]'></td>
<td><input type="text" name='item[$varline][quantity]'></td>
<td><input type="checkbox" name="item[$varline][check-tab1]"></td>
</tr>
</tbody>
</table>
I need to save the data to the DB using POST method...I am using the following javascript to calculate the totals:
function calcTot(i){
unitPrice = document.getElementById("myTable").rows[i].cells[1].childNodes[0].value;
quantity = document.getElementById("myTable").rows[i].cells[2].childNodes[0].value;
amount= parseFloat(price) * parseFloat(quantity);
document.getElementById("myTable").rows[i].cells[3].childNodes[0].value = amount.toFixed(2);
}
The PHP code that I have constructed so far is given below:
if (isset($_POST['submit'])) {
$reservation_id = $_POST['res_id'];
$item_id = $_POST['item']['product_id'];
$item_quantity = $_POST['item']['quantity'];
$item_discount = $_POST['item']['discount'];
$item_unit_price = $_POST['item']['price'];
$item_amount = $_POST['item']['amount'];
$items_total = $_POST['item']['total'];
$items_checked = $_POST['checked_pro'];
$invoiceId = $_POST['invoice_id'];
foreach ($item_id as $key => $value) {
$check_item_id = "SELECT item_id from products where item_id='" . $conn->real_escape_string($item_id[$key]) . "'LIMIT 1"; //check if item exist
$resultset = $conn->query($check_item_id);
if ($resultset->num_rows == 0) {
$insert_product = "INSERT INTO `invoice_items` (`id`, `invoice_id`, `product_id`, `quantity`, `price`, `amount`) VALUES (NULL, '" . $conn->real_escape_string($invoiceId) . "', '" . $conn->real_escape_string($item_id) . "', '" . $conn->real_escape_string($item_quantity) . "', '" . $conn->real_escape_string($item_unit_price) . "', '" . $conn->real_escape_string($item_amount) . "')";
$insert_item = mysqli_query($conn, $insert_product);
if (!$insert_item) {
echo "<script>";
echo "alert('Error inserting!')";
echo "</script>";
}
}

Related

passing dynamic data to ajax request to retrieve mysql data

I have a data from mysql database. I these data comes with a individual unique ids in a table format, when i click on a particular table row, i want to post that id via ajax and append the result in a div.
code for search and retrieving data from mysql
<?php
require ('config/searchConfig.php');
$return = '';
if(isset($_POST["query"]) && !empty($_POST['query']))
{
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query = "SELECT * FROM products WHERE productName LIKE '%".$search."%' ORDER BY ID DESC " ;
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
$return .='
<div class="table-responsive">
<table class="table table-striped">
<tr>
<th>Product Name</th>
<th>Price</th>
</tr>';
while($row1 = mysqli_fetch_array($result))
{
$return .= '
<tr id="add-btn" style="height:5em;" >
<td id="getID" value='.$row1["ID"].'>'.$row1["ID"].'</td>
<td id="productName" value='.$row1["productName"].'>'.$row1["productName"].'</td>
<td id="price" value='.$row1["price"].'>GHC '.$row1["price"].'.00</td>
</tr>
';
}
'</table></div>';
echo $return;
}
else{
echo 'No product Found with that Name';
}
}
?>
code for appending the result in a div when you click on the table row.
<script type="text/javascript">
$(document).on('click', '#add-btn', function() {
var getID = $('#getID').attr('value');
$.ajax({ //create an ajax request to display.php
url:"getPrice.php",
method:"GET",
data:{getID:getID},
success: function(data){
$("#dynamicAddRemove").append(data);
}
});
});
</script>

Toggle html attribute contenteditable in php dynamically created table

I found plenty of articles and solutions but for some reason my code still doesn't work. What am I missing?
Table: (creation works, important part is at the comment '! HERE')
<!-- Table with grades -->
<table class="table table-hover table-dark">
<caption>List of grades</caption>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Grade</th>
</tr>
</thead>
<tbody>
<?php
// fill table with data of database
if($subject != '') {
$query = "SELECT u.firstname, u.lastname, u.username, s.subject, g.grade FROM tbl_grades as g INNER JOIN tbl_users as u on g.studentID = u.ID INNER JOIN tbl_subjects as s on g.subjectID = s.ID where s.subject = ? and classID = ? order by u.lastname";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $subject, $class);
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows > 0) {
$count = 0;
while($row = $result->fetch_assoc()){
if(($count % 2) != 0) {
echo '<tr class="bg-success">';
} else {
echo '<tr>';
}
echo '<th scope="row">' . ($count + 1) . '</th>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
//! HERE
echo '<td class="grade_td" contentEditable="false">' . $row['grade'] . '</td>';
echo '</tr>';
$count++;
}
}
$result->free();
}
?>
</tbody>
</table>
<button class="btn_edit">Edit List</button>
Toggle with javascript, jquery (multiple versions, none of them work):
$(document).ready(function() {
// v1
$('.btn_edit').click(function() {
if($('.grade_td').contentEditable == false) {
$('.grade_td').contentEditable = true;
}
});
// v2
$('.btn_edit').click(function() {
$('td[contenteditable="false"]').contentEditable = true;
});
// v3
$('.btn_edit').click(function() {
$('.grade_td[contenteditable="false"]').contentEditable = true;
});
// more variations, same concepts
});
btw. the button event works fine
You need to use the jQuery attr function or set the attribute value on the element itself not the jQuery object.
$('.btn_edit').click(function() {
$('.grade_td').attr('contenteditable', 'true') ;
});
I'm not sure about custom attributes, but I would have made this a data attribute:
echo '<td class="grade_td" data-contenteditable="false">' . $row['grade']
and then referenced like this:
$('td.grade_td[data-contenteditable="false"]');

How to send dynamically generated values of a table back to the server?

I have my index.php where I'm going to make an Ajax request to the server and display the response (as a table).
<div id="result"></div>
<script>
$('#loading-image').show();
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data();
</script>
result will have the value of $output:
<?php
include '../../variables.php';
include '../../_Database.php';
$db = Database::getInstance();
$minDuration;
$maxDuration;
$tableRowCounter;
$output = '<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Artikel</th>
<th scope="col">Durchlaufzeit</th>
<th scope="col">Neue Durchlaufzeit</th>
<th scope="col">Bestätigen</th>
</tr>
</thead>
<tbody>
';
$result = mysqli_query($db->link, "SELECT * FROM `Person_changes_Article`");
while ($row = mysqli_fetch_assoc($result))
{
$result2 = mysqli_query($db->link, "SELECT * FROM `Article`");
while ($row2 = mysqli_fetch_assoc($result2))
{
if ($row['Article_idArticle'] == $row2['idArticle'])
{
$minDuration = ($row2['duration'] / 10) * 9;
$maxDuration = ($row2['duration'] / 10) * 11;
if ($row['newDuration'] < $minDuration OR $row['newDuration'] > $maxDuration)
{
$tableRowCounter++;
$output .= '
<tr>
<th scope="row">'.$tableRowCounter.'</th>
<td>'. $db->getArticleString($row2["idArticle"]) ." - " . $row2["idArticle"]. '</td>
<td>'. $row2["duration"] .'</td>
<td>'. $row["newDuration"] .'</td>
<td><input type="checkbox" id="t'. $tableRowCounter .'" name="name" value="value"></td>
</tr>
';
}
}
}
}
$output .= '
</tbody>
</table>';
echo $output;
?>
I intend to add checkboxes to each row in the table. Where a user simply can make a choice which rows should be changed and sent back to the server.
I don't know how to get the values out of the td's.
I tried to assign an automatically generated id to each checkbox with $tableRowCounter.
However, when I try to access the id of let's say #t1 with jquery it doesn't work.
like so:
$(document).ready(function(){
$('#t1').prop('checked', true);
});
After all, it just feels bad preparing auto-generated id values in the backend.
What I want to do is (or the user) to check checkboxes of any row, and hit a button which sends the values in the table of that specific row to the server.
It doesn't even matter how the server is receiving the data. I'd be totally fine with an array of all the values from all rows of the table (just the checked ones though)
How? Please help.
First, for the third code snippet, the $('#t1') was unavailable because the table was not rendered when document was ready. The table was inserted after the AJAX request response. If you want to initialize something, do it in the AJAX request success callback.
For submitting the checked rows, attribute selector is recommended.
the html output:
$output .= '
<tr>
<th scope="row">'.$tableRowCounter.'</th>
<td>'. $db->getArticleString($row2["idArticle"]) ." - " . $row2["idArticle"]. '</td>
<td>'. $row2["duration"] .'</td>
<td>'. $row["newDuration"] .'</td>
<td><input type="checkbox" data-id="'. $row['id'] .'" name="name" value="value"></td>
</tr>';
then the button handler:
$("#submit").onclick(function() {
var selectedIds = []
$("table input[type=checkbox]").forEach(function(i, elem) {
var cb = $(elem)
if (cb.prop('checked')) {
selectedIds.push(cb.attr('data-id'))
}
// send selectedIds to server
})
})
#cuiyajie
Thank you. I couldn't completely apply your solution to my problem.
However, I saw how it's made and wrote it again on my level of understanding JavaScript.
I know this shouldn't be made, but I didn't see any reason why I would run into issues having not unique IDs
I have given my tds IDs. like so:
<tr>
<th scope="row">'.$tableRowCounter.'</th>
<td>'. $db->getArticleString($row2["idArticle"]) .'</td>
<td id="article">'. $row2["idArticle"] .'</td>
<td id="duration">'. $row2["duration"] .'</td>
<td id="newDuration">'. $row["newDuration"] .'</td>
<td>'. $db->getName($row["Person_idPerson"]) . " ".$db->getLastName($row["Person_idPerson"]) .'</td>
<td id="check"><input type="checkbox" id="check" name="name" value="value"></td>
</tr>
I can then easily loop through the tds and push the values into arrays:
var article = [];
var duration = [];
var newDuration = [];
var check = [];
$("td[id='article']").each(function(){
article.push($(this).text());
})
$("td[id='duration']").each(function(){
duration.push($(this).text());
})
$("td[id='newDuration']").each(function(){
newDuration.push($(this).text());
})
$("input[id='check']").each(function(){
if ($(this).is(':checked')){
check.push(1);
}else{
check.push(0);
}
})
And post the arrays using Ajax
$.ajax({
type:'POST',
url:'storeData.php',
data: { article: article,
duration: duration,
newDuration: newDuration,
check: check
},
success:function(data){
//alert(data)
},
});
in storeData.php I can then work with those arrays and do whatever I want
$article = $_POST['article'];
$duration = $_POST['duration'];
$newDuration = $_POST['newDuration'];
$check = $_POST['check'];
print_r($article);
print_r($duration);
print_r($newDuration);
print_r($check);

How can I extract JSON data from PHP and display it in a datatable?

I want to get reports from my database by using PHP via turning it into JSON format and displaying it with AJAX JQuery. But I can't seem to pass the data correctly. Can somebody please tell me my fault?
Here is my code view:
$(document).ready(function() {
$("#searchOverall").click(function() {
var ay = $("#Overall_acadyear").val();
var year = $("#Overall_year").val();
if (ay === undefined || ay == '') {
alert("Select Academic year.");
} else if (year === undefined || year == '') {
alert("Select year level.");
} else {
$.ajax({
url: "js/overallreport.php",
dataType: "json",
data: "ay=" + ay + "&year=" + year,
success: function(data) {
//left this blank because I am not sure of what I am doing.
//I used $.getJSON and $.each
},
error: function() {
alert('Cannot retrieve data from server.');
}
}); //ajax
} //else
}); //btnOverall
});
//This is the JS FILE
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<select class="form-control" id="Overall_acadyear">
<option value='' active>Select AY</option>
<?php $r->selectAcademicYear(); ?>
</select>
<select class="form-control col-sm-4" id="Overall_year" align="right">
<option value='' active>Select year level</option>
<?php $r->selectYear(); ?>
</select>
<div class="form-group">
<button type="button" class="control-label btn-success" id="searchOverall" name='createAccount'>Search</button>
<button type="reset" class="control-label btn-danger" id="reset">Clear Fields</button>
</div>
</th>
</tr>
<tr>
<th>Student Number</th>
<th>Student Name</th>
<th>Section</th>
<th>Status</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody> <!--This is the view file -->
<?php
require($_SERVER['DOCUMENT_ROOT']."/finalsis/include/config.php");
include_once($_SERVER['DOCUMENT_ROOT']."/finalsis/include/class.utility.php");
header("Content-Type: application/json");
$ay = $_GET['ay'];
$year = $_GET['year'];
$ay = $obj->cleanString($ay);
$year = $obj->cleanString($year);
$conn = mysqli_connect(db_server,db_user,db_password,db_database);
$ay = mysqli_escape_string($conn,$ay);
$year = mysqli_escape_string($conn,$year);
$selectSQL = "SELECT studentlevel_student, student_fname, student_mname, student_lname,
section_name, student_status FROM tblstudentlevel inner join
tblstudent on studentlevel_student = student_number inner join
tblyearsection on studentlevel_ys = ys_id WHERE studentlevel_acadyear = '" .$ay."' AND year_name = '" .$year. "'";
$result = mysqli_query($conn,$selectSQL);
$output = '{"student": [';
while($rs = mysqli_fetch_array($result)){
$name = $obj->getFullName($rs['student_fname'],$rs['student_mname'],$rs['student_lname']);
$output .= '{"sno":"' .$rs['studentlevel_student']. '", ';
$output .= '"name":"' .$name. '", ';
$output .= '"section":"' .$rs['section_name']. '",';
$output .= '"status":"' .$rs['student_status']. '"},';
}
$output .= "]}";
mysqli_close($conn);
echo json_encode($output);
//This is where my data gathering happens. ?>
Problem is in the following line:
echo json_encode($output);
json_encode needs an array. You are passing string.
$jsonData = array();
while($rs = mysqli_fetch_array($result)){
$name = $obj->getFullName($rs['student_fname'],$rs['student_mname'],$rs['student_lname']);
$jsonData[] = array(
'sno' => $rs['studentlevel_student'],
'name' => $name,
);
}
echo json_encode($jsonData);

SQL UPDATE select w/ multiple to a PHP array

I'm aware of the SQL injection issues in this code. I am however focusing on just trying to get form to update the mySQL server. I have two select boxes that are populated. I can transfer the equipment back and forth between the two. However when I go to update It does not work. PLEASE HELP ME!
HERE is FORM:
$connection = mysql_connect('#', '#', '#');
mysql_select_db('#');
$techequipment = "SELECT serial, type_id FROM tbl_assets WHERE user_id = {$_GET ['TechID']} AND date_installed IS NULL AND date_returned IS NULL AND metro_date_returned IS NULL ORDER BY type_id, serial";
$techresult = mysql_query($techequipment);
$jobequipment = "SELECT serial, type_id FROM tbl_assets WHERE account_number = {$_GET ['JobNum']} ORDER BY type_id, serial";
$jobresult = mysql_query($jobequipment);
$link = array($_GET ['JobNum'])
?>
<title>Assign Equipment</title>
<table align="center">
<form action="assigned_equipment.php?<? echo http_build_query($link)?>" method="POST">
<tr>
<td><center><b><?php echo "Tech #"; echo $_GET ['TechID']; echo " Assigned Equipment"; ?></b></center></td>
<td></td>
<td><center><b><?php echo "Job #"; echo $_GET ['JobNum']; echo " Assigned Equipment"; ?></b></center></td>
</tr>
<tr>
<td>
<select name="tech[]" size=20 multiple id="list1" STYLE="width: 350px">
<?php $i=0; while($row = mysql_fetch_array($techresult)) { ?>
<option value="<?=$row["serial"];?>"> <?=$row["type_id"]." - ".$row["serial"];?></option>
<?php $i++; } ?> </select>
</td>
<td>
<center><input type="button" id="btnAdd" value="Transfer >>"/></center>
<center><input type="button" id="btnRemove" value="<< Transfer"/></center>
</td>
<td>
<select name="job[]" size=20 multiple id="list2" STYLE="width: 350px">
<?php $i=0; while($row = mysql_fetch_array($jobresult)) { ?>
<option value="<?=$row["serial"];?>"> <?=$row["type_id"]." - ".$row["serial"];?></option>
<?php $i++; } ?> </select>
</td>
</tr>
<tr>
<td colspan="2">
</td>
<td>
<center><input type="submit" value="SUBMIT"/></center>
</form>
</td>
</tr>
<tr>
<td colspan="3">
<center>Multi Select: Press & hold [CTRL] while clicking on the items.</center>
</td>
</tr>
<tr>
<td colspan="3">
<center>EXIT</center>
</td>
</tr>
</table>
<script src="js/jquery-2.2.0.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(
function () {
//TAKE EQUIPMENT FROM TECH AND PUT IT IN JOB BOX
$('#btnAdd').click(
function (e) {
$('#list1 > option:selected').appendTo('#list2');
e.preventDefault();
});
//TAKE EQUIPMENT FROM JOB AND PUT IT IN TECH BOX
$('#btnRemove').click(
function (e) {
$('#list2 > option:selected').appendTo('#list1');
e.preventDefault();
});
});
</script>
Here is my assigned_equipment.php file:
<?php
$connection = mysql_connect('#', '#', '#')
or die('Could not connect: ' .mysql_error());
mysql_select_db('#');
$equipmentquery="UPDATE tbl_assets SET date_installed = curdate(), account_number = {$_GET['0']} WHERE serial = $_POST['job']";
$techquery="UPDATE tbl_assets SET date_installed = curdate(), account_number = {$_GET ['0']} WHERE serial = $_POST['tech']";
?>
Ok, you are right it seems to be the case that "0" is a valid variable name to submit via $_GET or $_POST. So this is not a problem.
But your problem is that $_POST['job'] is an array.
You try to do this:
$equipmentquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = {$_GET['0']} "
. "WHERE serial = $_POST['job']";
While $_POST['job'] is an array you cannot do it like this!
Please try the following:
$jobnum = (int)$_GET['0'];
$job_arr = $_POST['job'];
if(($jobnum > 0) && is_array($job_arr) && (count($job_arr) > 0)) {
$equipmentquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = ".$jobnum." "
. "WHERE "
. 'serial IN ("'.implode('","',$job_arr).'") ';
}
Ok what happens here?
I suspect that your serial holds the values posted in job array.
So you want to update each row where your serial matches the posted values in your array.
In case of your $_POST: Array ( [job] => Array ( [0] => gi4416ncd876 [1] => GI4521NA3391 [2] => M40719GD6274 [3] => PAEH01734539 ) ) and your $_GET: Array ( [0] => 113852 ) it will result in the following query:
UPDATE tbl_assets
SET date_installed = curdate(),
account_number = 113852
WHERE serial IN ("gi4416ncd876","GI4521NA3391",
"M40719GD6274","PAEH01734539")
Ok now you have a working query.
Not it is time to execute it!!!
therefore you need to:
$result = mysql_query ( $equipmentquery );
this is the important line, you are missing!
Finally your code may look like this:
<?php
$connection = mysql_connect('#', '#', '#')
or die('Could not connect: ' .mysql_error());
mysql_select_db('#');
$jobnum = (int)$_GET['0'];
$job_arr = $_POST['job'];
$tech_arr = $_POST['tech'];
if(($jobnum > 0) && is_array($job_arr) && (count($job_arr) > 0)) {
$equipmentquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = ".$jobnum." "
. "WHERE "
. 'serial IN ("'.implode('","',$job_arr).'") ';
$result1 = mysql_query ( $equipmentquery );
}
if(($jobnum > 0) && is_array($tech_arr) && (count($tech_arr) > 0)) {
$techquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = ".$jobnum." "
. "WHERE "
. 'serial IN ("'.implode('","',$job_arr).'") ';
$result2 = mysql_query ( $techquery );
}
When this works, you should directly switch to mysqli or pdo!
mysql_ functions are deprecated and not present any more in the latest php version! You should really care about sql injection! So use prepared statements to clean up your input data!!! There are various tutorials out there!!! DO NOT USE THIS CODE IN A LIVE ENVIRONMENT

Categories