UPDATE: for some reason the php file won't read the mysqli_query statment.
I have a dynamically filled table that has an input box to input a certain quantity amount in order to move a part to a different location with that quantity. Right now I am just trying to get the update code to work to update the current amount based on the inputted amount. Eventually I will add the ability to insert a new row into MySQL based on the inputted amount and inputted location.
It seems to be accessing the update.php file but have had no luck in the MySQL database being updated. I'm not sure how to send the data to the php file in order to update the appropriate rows.
This is my webpage:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<?php
if (isset($_GET['Placeid'])){
$moveplace = $_GET['Placeid'];
$sql = "SELECT *
FROM Parts p, Locations l
WHERE Placeid = '$moveplace' and p.locationid = l.locationid";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0){
while ($row = mysqli_fetch_assoc($result)){
<form onsubmit='updatetable()'
<table id='tablerun' class=searcht style='background-color:$bgcolor'>
<tbody>
<tr>
<td id='row1' value='".$row['id']."' name='moveid' style='display:none'>".$row['id']."</td>
<td value='".$row['PartNum']."' name='movepart'>".$row['PartNum']."</td>
<td value='".$row['ModelNum']."' name='movemodelnum'>".$row['ModelNum']."</td>
<td>".$row['Country']."</td>
<td>".$row['Region']."</td>
<td>".$row['Location']."</td>
<td>".$row['Placeid']."</td>
<td style='width:100px' value='".$row['UnitNum']."' name='moveunitnum'>".$row['UnitNum']."</td>
<td id='val' style='width:50px;' value='".$row['QTY']."' name='moveqty'>".$row['QTY']."</td>
<td value='0' type=text id='amt' name='moveamt'></td>
</tr>
</tbody>
</table>
</div>";
}
echo "<tr><td></td><td><input type='submit' class='submit' ></td></tr></form>";
}
}
?>
<script type="text/javascript">
function updatetable(){
$('#tablerun tr').each(function(){
var row_id = $(this).find("td:eq(1)").text();
var quantity = $(this).find("td:eq(8)").text();
var amt = $(this).find("input:eq(0)").val();
var data = {
id : row_id,
qty : quantity,
amt : amt
};
$.ajax({
type: "POST",
url: "update.php",
data: data,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
});
};
</script>
update.php:
<?php
include_once 'includes/database.inc.php';
$id = $_POST['moveid'];
$qty = $_POST['moveqty'];
$amt = $_POST['moveamt'];
$sql = "UPDATE parts set QTY = $qty - $amt where id = $id";
mysqli_query($conn, $sql) or die(mysqli_error($conn));
?>
P.S. I realize that I should be using prepared statements I plan on implementing them once I have completed this task.
Any help is appreciated
Related
I am trying to print on a thermal printer, this, after performing a query and obtaining certain data, which I send to a hidden input, the problem is that I do not know how to insert and use the second ajax post to my file php for printing, I am using the Mike42 ECPOS library. would you be so kind to guide me?
function calcCredits(){
/* variables from inputs */
var last_credit= parseInt(document.getElementById("studentcredits").value);
var namesec= document.getElementById("studentqr").value;
var credits= parseInt(document.getElementById("money").value);
var total_pay = credits * 35;
var ttl_credits = last_credit + credits;
/* Beggin Ajax */
$.ajax({
url:'addcredits.php',
type:'post',
data:{namesec:namesec,credits:credits},
success:function(data){
$.ajax({
url: 'ticket.php',
type: 'POST',
success: function(response){
alert('Printing....');
}
});
}
});
}
this is the php that performs the search and shows the results
<?php
require 'database.php';
$con = new Database();
$pdo = $con->conectar();
$campo = $_POST["campo"];
$sql = "SELECT * FROM students WHERE student_qr LIKE ? OR student_secondname LIKE ? ORDER BY student_secondname ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->execute([$campo . '%', $campo . '%']);
$html = "";
$data_query['result'] = $html;
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$html .= "
<div class=\"container-fluid \">
<div class=\"row\">
<div class=\"col-lg-12\">
<table class=\"table table-hover\">
<tr >
<th scope='col'>Grupo</th>
<th scope='col'>Nombre</th>
<th scope='col'>Créditos</th>
</tr>
<tr>
<td id='list_id'>".$row["student_group"]."</td>
<td id='list_id'>".$row["student_name"]." ".$row["student_secondname"]." ".$row["student_lastname"]."</td>
<td id='list_name'>".$row["student_credits"]."</td>
<td id='list_credits' style=\"cursor: pointer\" onclick=\"mostrar('" .$row["student_qr"] ."'), mostrar2('" .$row["student_credits"] ."')\"><button type='button' class='btn btn-warning' id= 'show' onclick='show()' >Añadir Creditos</button></td>
</tr>
</table>
</div>
</div>
</div>
";
}
echo json_encode($html, JSON_UNESCAPED_UNICODE);
and this is for printing
<?php
require __DIR__ . '/ticket/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
$nombre_impresora = "POS";
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->setJustification(Printer::JUSTIFY_LEFT);
$printer->text("Producto Galletas\n");
$printer->text( "2 pieza 10.00 20.00 \n");
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Muchas gracias por su compra\n");
$printer->feed(3);
$printer->close();
?>
sorry if it is not well structured I'm still practicing, thanks
After the comments and contributions that helped me a lot, I noticed that my mistake was to forward the info to another file, when the printing could be treated within the first insertion php, so I added the ticket code and that's it.
this is the ajax function
function calcCredits(){
$.ajax({
/* Se envian datos por POST a PHP */
url:'addcredits.php',
type:'post',
dataType: 'json',
data:{
studentqr:$('#studentqr').val(),
credits:$('#credits').val(),
},
})
.always(function(){
console.log("complete");
});
}
and then, the php insert
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("conection.php");
include("ticket/autoload.php");
$credits = mysqli_real_escape_string($con, $_POST['credits']);
$studentqr = mysqli_real_escape_string($con, $_POST['studentqr']);
$stmt = $con->prepare("UPDATE students
SET student_credits = (student_credits + ?)
WHERE student_qr = ?");
$stmt->bind_param("is", $_POST['credits'], $_POST['studentqr']);
$stmt->execute();
$insert_query = $con->prepare("INSERT INTO historical_credits (id_student, credits_paid)
SELECT id_student, ?
FROM students
WHERE student_qr = ?");
$insert_query->bind_param("is", $_POST['credits'], $_POST['studentqr']);
$insert_query->execute();
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
$nombre_impresora = "Termica";
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->setJustification(Printer::JUSTIFY_LEFT);
$printer->text("Producto Galletas\n");
$printer->text( "2 pieza 10.00 20.00 \n");
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Muchas gracias por su compra\n");
$printer->feed(3);
$printer->close();
$archivoActual = $_SERVER['PHP_SELF'];
header("refresh:2;url= + $archivoActual ");
mysqli_close($con);
?>
thanks a lot for your time
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>
I have a group of dropdowns with a list of players. When a player is selected, their 'Value' should appear next to the drop down and the Total should update to be the sum of all selected players values.
php code below is for two players but I have ten, will likely have ten different similar functions for each of the dropdowns
select-player.php
<!--player1-->
<tr>
<td style="width:50%;">
<select name="player1" id="player1" onchange="showvalue1()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value1">
</td>
</tr>
<!--player2-->
<tr>
<td style="width:50%;">
<select name="player2" id="player2" onchange="showvalue2()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value2">
</td>
</tr>
<tr>
<th style="width:50%";>Total</th>
<th style="width:50%;" id="total"></th>
</tr>
ajax.js
function showvalue1(){
var x = document.getElementById("player1").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value1").html(data.price);
$("#total").html(data.newtotal);
}
})
}
function showvalue2(){
var x = document.getElementById("player2").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value2").html(data.price);
$("#total").html(data.newtotal);
}
})
}
I've read that jsonencode is used to send arrays back that I can then assign to IDs in js.
showvalue.php
<?php
include_once 'includes/dbh.inc.php';
$pl = $_POST['id'];
$pl = trim($pl);
$total = 0;
$total = $_POST['total'];
$sql = "SELECT value FROM players WHERE playername='{$pl}'";
$result = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_array($result)){
$newtotal = 0;
$value = $rows['value'];
$newtotal = $total + $value;
$ret = array('price'=>$value, 'newtotal'=>$newtotal);
echo json_encode($ret);
}
?>
Not getting any errors or console returns but also no values are being returned.
What am I missing?
Checking your HTML source, #total is a table cell:
<th id="total"></th>
And you are retrieving it using .value:
var t = document.getElementById("total").value;
But .value is for inputs, not text in a table cell, so that won't work.
To get the text, using jQuery instead of vanilla JS (since the rest of your code is jQuery):
var t = $('#total').text();
I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.
When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
I am practising AJAX by implementing editable HTML table looking like this:
The logic is this:
User clicks on left column (containing integer);
JS script catches its value and by using AJAX adds them to database;
PHP script fetches this value, makes some calculations, adds them to database and shows result in right column (date in <td>).
Now as expected PHP script needs page refreshing to show calculation result (date in <td>). I'm trying to write JS script which will retrieve calculated data from database and immediately show in HTML table's cell.
Having troubles with it. Asking for help with this issue.
index.php:
<form id="form-wrap" action="functions.php" method="POST">
<select name="select1" required>
<?php
for ($i = 1; $i <= 20; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
<br>
<input type="text" id="name" name="name">
<input type="date" id="day" name="day">
<input type="submit" name="button_ok" id="button_ok" value="Write">
<input type="submit" name="show" id="show" value="Show table">
</form>
functions.php:
<?php
require_once 'dbconnect.php';
$loged = $_POST["name"];
$day = $_POST["day"];
class Count_Add_Class {
public function CountDays() {
global $day, $loged, $day_remind1, $days_before1;
$currenttime = time();
$days_before1 = $_POST["select1"];
// ... make some calculations with user's input ...
$this->AddDate();
}
public function AddDate() {
global $pdo, $loged, $day, $day_remind1, $days_before1;
if (isset($_POST['button_ok'])) {
// ... insert in database user's inpt and calculation result ...
}
}
}
$obj = new Count_Add_Class();
$obj -> CountDays();
function Count_days_new_data() {
global $pdo, $day, $loged, $day_remind1_updated,
$stmt = $pdo->prepare("SELECT select1 FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $row) {
$day_remind1_updated = $row['select1'];
}
$day_remind1_updated = $day - ($days_before1_updated * 86400);
$day_remind1_updated = date('Y-m-d', $day_remind1_updated);
}
Count_days_new_data();
function Show() {
global $pdo, $loged, $faq, $day_remind1_updated;
$stmt = $pdo->prepare("SELECT * FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$faq = $stmt->fetchAll();
$s1 = $_POST['editval'];
$id = $_POST['id'];
$stmt2 = $pdo->prepare("UPDATE tablex SET select1=? WHERE
id=?");
$stmt2->execute([$s1, $id]);
$stmt3 = $pdo -> prepare("UPDATE tablex SET day_remind1=?,WHERE
id=?");
$stmt3->execute([$day_remind1_updated, $id]);
require_once 'table.php';
}
Show();
?>
table.php:
<div id="day-data">
<tbody>
<?php
foreach($faq as $key=>$value) {
?>
<tr class="table_row">
<td><?php echo $value['name']; ?></td>
<td aria-label="First" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $faq[$key]["id"];
?>')" onClick="showEdit(this);"><?php echo $faq[$key]["select1"]; ?>
</td>
<td><?php echo $value['day_remind1']; ?></td>
</tr>
<?php
}
?>
edit.js:
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat
right");
$.ajax({
url: "functions.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
show.js: (inspired by this answer)
$(".tbl tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the
clicked tr
var value = $(this).find("td")[1].text()
$.ajax({
url : "table.php",
dataType: "text",
success : function (data) {
$(".day-data").html(data);
},
error: function (data) {
(".tbl").html('No such file found on server');
}
});
});
When user clicks on HTML-table left column it is higligted well; when he changes it, data is addiing to database well. Now when page is refreshed new data is calculated, added to database and shown in HTML-table's right column.
I suppose problem is in show.js. Need some help in correcting this script!
Update1:
Added illustartion of my task's logic:
It is unfortunate, that you have everything in the functions.php file. It doesn't just count the values, it also renders the table. So when you call the function saveToDatabase, the request that you make to functions.php (and i understand it coorectly) already returns the table with the updated data (as argument of the success function). Try removing show.js and changing the success function content in edit.js from this:
$(editableObj).css("background","#FDFDFD");
to this
$(editableObj).css("background","#FDFDFD");
$(".day-data").replaceWith(data);