I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Related
I am building a warranty product website as a side project for a small business I work at (We deal with batteries for cars, heavy equipment...). There is a lot going on here.
Basically, when an item gets returned for a warranty inspection the user can input the customer's information and the product information for it to be tracked and managed. I began with making a database in PHP (It is only one table and not fully normalized since it really does not need to be unless there is expansion later on) with only one table that manages transactions.
Each transaction when submitted defaults to ACTIVE status meaning it can be manipulated (Deleted, resolved, or to add a comment) via buttons in the table. To be able to do this I have been using AJAX to be able to use buttons in a table and change the Status to DELETED or RESOLVED.
Now, there are four pages of tables (Like ALL, ACTIVE, DELETED, and RESOLVED) and each ran a very similar code (While loop that displayed the table) with the expectation of the SQL statement. For example the ALL inspections table has nowhere clause in the SQL statement, while the ACTIVE Inspections table would have a where Status = "ACTIVE", as so on for resolved and deleted. Since displaying the data seemed repetitive to have a while loop, I decided to make one table.php page with a function call GetTableData and on each page (ACTIVE, ALL, DELETED...) I would include the PHP file, and then call and pass through the SQL statement, like so...
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Battery Wholesale Inspection Database</title>
</head>
<?php include 'headernNavbar.html'; include 'Actions/connection.php'; include 'Actions/table.php'?>
<body>
<h1 id="title">Active Inspection Database</h1>
</body>
</html>
<?php
$sql = "SELECT TransactionID, CustomerName, PhoneNumber, ReceivedDate, Item, DATE_FORMAT(ManufactureDate, '%m-%y') as Age , InitalVoltage, InitalCCA, Comments, WarrStatus FROM inspection.product WHERE product.WarrStatus = 'ACTIVE' ORDER BY ReceivedDate DESC";
GetTableData($sql, $conn);
?>
Here is what the table.php file looks like...
<html>
<head>
<title></title>
</head>
<?php
include 'Actions/connection.php';
function GetTableData($sql, $conn){
$result = mysqli_query($conn, $sql);
echo "<table id='inspectTable' class='inspectTable'>";
echo "<thead><tr>";
echo "<th>Customer</th>";
echo "<th>Phone</th>";
echo "<th>Received</th>";
echo "<th>Item</th>";
echo "<th>Age</th>";
echo "<th>Voltage</th>";
echo "<th>CCA/AH</th>";
echo "<th>Comments</th>";
echo "<th>Status</th>";
echo "<th colspan=3 >Tools</th>";
echo "</thead></tr>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
echo "<tbody class='dbTable'>";
while($row = mysqli_fetch_assoc($result)) {
$id= $row['TransactionID'];
echo "
<tr><td>" . $row['CustomerName'] ."</td>
<td>" . $row['PhoneNumber'] . "</td>
<td>" . $row['ReceivedDate'] . "</td>
<td>" . $row['Item'] . "</td>
<td>" . $row['Age'] . "</td>
<td>" . $row['InitalVoltage'] . "</td>
<td>" . $row['InitalCCA'] . "</td>
<td>" . $row['Comments'] ."</td>
<td>" . $row['WarrStatus'] ."</td>";
if ($row['WarrStatus'] == 'ACTIVE'){
echo "<td><button class='deleteRow' id='".$id."' >Delete</button></td>
<td><button class='updateRow' id='".$id."' >Update</button></td>
<td><button class='resolveRow' id='".$id."' >Resolve</button></td>";
}
else{
echo "<td><button class='deleteRow' id='".$id."' disabled >Delete</button></td>
<td><button class='updateRow' id='".$id."'disabled >Update</button></td>
<td><button class='resolveRow' id='".$id."'disabled>Resolve</button></td>";
}
}
echo "</tbody>";
} else {
echo "Not Data Avaibable.";
}
}
?>
<script>
$(".deleteRow").click(function()
{
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'Action/deleteAction.php',
data:'id='+del_id,
success: function(data)
{
location.reload();
}
});
});
$(".resolveRow").click(function()
{
var del_id = $(this).attr('id');2
$.ajax({
type:'POST',
url:'resolveAction.php',
data:'id='+del_id,
success: function(data)
{
location.reload();
}
});
});
</script>
</html>
So, as an example when the user is on the ACTIVE inspections page, and the list gets called it is displayed. When the user wants to delete an entery and clicked delete, the deleteAction.php should be called and changes the status from ACTIVE to DELETE. Here is the php for that...
<html>
<head>
<title>delete action</title>
</head>
<?php include 'connection.php'?>
<?php
$id = $_POST['id'];
$sql = "UPDATE inspection.product
SET DeletedDate = now(), WarrStatus = 'DELETED'
WHERE TransactionID = $id";
mysqli_query($conn,$sql);
?>
</html>
Now here is the problem I am facing. When a button (For example the delete button) is clicked nothing changes. Unlike when I first had the while loop (in the table.php) on each page with the AJAX js stuff it worked like a charm. I am just not sure if I am missing something. Here are the things I have tried:
Had each while loop and SQL statement in each PHP page with the AJAX
Created a separate js file and referenced that in the table.php, as well as each PHP page
Only had the AJAX js stuff in the other pages but still called the GetTableData
I have also not accomplished the updating comment button as of yet
Could anyone let a hand here? I would greatly appreciate it! If you see any other things I should do to improve I would also appreciate that. This is my first web project out of the first year!
EDIT:
I also forgot to include that reference to ajax in the table.php, it is there on my system, but I was playing around and forgot to add it in the post! This didn't fix the issue.
EDIT:
So after playing around with it, it does work when putting the ajax js in each php file, however it does not work when I have a separate js file and including that into each php file. Is there a different way to do this for it is a little cleaner?
I'm having a few problems with my "architecture". I'm really rusty in this field.
So the code below is basically PHP that reads a database table and prints row by row (columns are "name" (text), and "votes" (int) ) with a button near each row which is named by the "name" column as in the table.
Very simple by now, works perfectly.
Now, each button should add +1 to a row in table in the database (to votes column), by the name of the button, simple, but since the number of buttons is not constant and is changing by the number of rows in each table (dynamic), I need to create a JS event that will get a button pressed with its name/value, and call a php function (I need specifically with functions) with the name as a variable (parameter), so it will add +1 to the votes where the name is the name pressed).
$allsql = "SELECT * FROM `voting` ORDER BY `voting`.`groupName` DESC, `voting`.`votes` DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="post" id="voting_area">';// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo 'name: ' .$name. ' - votes: ' .$votes. ' <button type="button" name="'.$name.'" value="'.$name.'">'.$name.'</button><br>';
}
echo '</form>';
}
Please try and explain me specifically each code (JS, AJAX, PHP).
I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you
You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
I'm trying to delete an entry in my database using the code below. The javascript function takes me to index.php?delpost= with the correct "adventureID" but when I check my database the row is still there. I've very recently started using PDO so I'm wondering if the execute() statement might be the issue. $dbh connect to my database at the top of the page and it is working as it prints every row from the table I'm trying to delete rows from. My goal is to successfully delete a row when I call the javascript function. The issue is - it doesn't.
<script language="JavaScript" type="text/javascript">
function delpost(adventureID, title)
{
if (confirm("Are you sure you want to delete '" + title + "'" + " '" + adventureID + "'"))
{
window.location.href = 'index.php?delpost=' + adventureID;
}
}
</script>
<?php
if(isset($_GET['delpost'])){
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
header('Location: index.php?action=deleted');
exit;
}
?>
<?php
if(isset($_GET['action'])){
echo '<h3>Post '.$_GET['action'].'.</h3>';
}
try {
foreach($dbh->query("SELECT adventureID, title, postDate FROM adventure ORDER BY adventureID DESC") as $row) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
?>
<td>
Delete
</td>
<?php
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Probably you are facing problem with MYSQL SAFE UPDATES being ON. To avoid it and be able to finally delete rows, you can engage in the following tactics:
SET SQL_SAFE_UPDATES = 0;
--- YOUR DELETE STATEMENT ---
SET SQL_SAFE_UPDATES = 1;
To check if you have SQL_SAFE_UPDATES enabled you can do by running:
SHOW VARIABLES LIKE 'sql_safe_updates'
Try to replace this code :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
By the following :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->bindParam('adventureID', $_GET['delpost']);
$stmt->execute();
Explanation :
You can either : Use ":variable" in your query, then pass variables by binding them with the "bindParam" function.
Or : Use "?" in your query, and then pass variables in the "execute" function.
Full example can be found here : http://php.net/manual/fr/pdostatement.execute.php#example-1050
I'm making this app to practice asynchronous websites, all it does is show the contents of a database table on the site in table format using jQuery and PHP.
Everything works perfectly, except I wanted to add a button on each < tr > that on click deletes the respective entry on the database, however, I can't seem to get it done. I've got through the documentation of everything I used and just don't see the problem. Here is my code:
HTML:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
The table is created on a separate PHP file that's called by ajax, this is the relevant loop:
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['ID']."</td>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
</td>';
echo "</tr>";
}
All buttons are created with the correct 'name' on the final html (that is an auto_increment number).
jQuery:
$(".deleteWaitlist").click(function(){
console.log("click on .deleteWaitlist");
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
console.log("success" + result);
}
});
});
As I said, kinda new to ajax. correct me if I'm wrong: this calls deleteWaitlist.php and posts a parameter 'id' with value '$(this).attr('name')' which is an auto_increment value on the database and should be diferent for every entry.
deleteWaitlist.php
$sql = "DELETE FROM waitlist WHERE id=" . $_POST[id] . "";
mysqli_query($c,$sql);
It's pretty straightforward, isn't it? Can you help me find the mistake? Maybe something like (int)$_POST[id] somewhere? I could swear I tried that everywhere.
EDIT: Strangely, Im not even getting the console log "click on .deleteWaitlist" when I click the button, as if I weren't even clicking it at all. What can be happening? I also changed the id "deleteWaitlist" for a class, since it seems to be the best practice.
Seems there is multiple delete button in your output html and jQuery matches exactly one element when querying for an ID.
Try use CLASS instead of ID on the delete button.
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['ID']."</td>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
</td>';
echo "</tr>";
}
jQuery:
$(".deleteWaitlist").click(function(){
console.log("click on .deleteWaitlist");
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
console.log("success" + result);
}
});
});