Deleting from a database - php

I am trying to print out data which is stored in my database and then delete an aspect of it. See below example:
Database includes: id, room, time, date
my code is is as follows:
<?php
$sql = "SELECT id, room, timers, dates, remove FROM groom WHERE person = $a";
$result = $conn -> query ($sql);
if($result -> num_rows >0){
?>
<?php
while($row = $result -> fetch_assoc()){
?>
<tr>
<td> <?php echo $row["room"] ?> </td>
<td> <?php echo $row["timers"] ?> </td>
<td> <?php echo $row["dates"] ?> </td>
<td> <?php echo "Glassrooms" ?> </td>
<td>
<?php
echo
"<form action='' method='post'>
<input type='submit' name='1' value='Delete' />
</form>";
if(isset($_POST['1']))
{
$r = $row["id"];
$sqli ="UPDATE groom SET remove = '$a' WHERE id = $r";
$resultt = $conn -> query ($sqli);
echo
"<form action='removalgr.php' method='post'>
<input type='submit' name='usen' value='Confirm Deletion' />
</form>";
}
?> </td> </tr>
What i am doing is selecting all the data from a database groom where it relates to the person logged in. It prints it out fine in the following format which is perfect:
Room Time Date Area DeleteBooking
1 4 2/3/17 BB Delete
And the where it says delete is a button which allows for the booking to be deleted. However my problem is this:
when there is more than one booking, they all delete because below they are being called the same thing. see here:
<input type='submit' name='useb' value='Delete' />
Is it possible to call the above name something different everytime, or alternatively call it the id of the booking?
Hopefully this makes sense and any help would be greatly appreciated!!
Thanks

Add a hidden input with the ID of the item to be deleted.
echo
"<form action='' method='post'>
<input type='hidden' name='id' value='{$row['id']}'>
<input type='submit' name='1' value='Delete' />
</form>";

Related

how to update table row data with unique id?

code:
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<form method="post" name="myform">
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
<?php
}
?>
</table>
</form>
In this code I want to update table enquires2 with unique id. In following image you see that table row having save button this is only one row similarly it have multiple row which having save button in each row. Now I want that when I click on save button of particular row only that row data will be update. How can I fix this problem ? Please help.
Thank You
You could use AJAX and jQuery to do this and send the data to a separate PHP file and assigning the $row['ID'] to a data-value attribute of the button,
$("#save-btn").click(function(){
id = $(this).attr(data-value);
***** rest of values here
$.ajax({
method: "GET",
data: {id: id, rest of: data here},
url: phpfile.php,
success: function(){
console.log("Success");
}
})
});
While in the PHP file you would take get the id like,
$_GET['id'], and same with the other values since we are using the GET method and then put them in the update query.
First of all, for security reason you need to change this query to a prepared statement see PHP MySQLI Prevent SQL Injection:
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
This line is bad anyway, you are missing a opening quote for $comment2.
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
Are you sure $link is an actual mysqli link?
As for the html part, you need to mkae one form for each record. See the link posted HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
alternatively you could do something bad like only adding the $id to evry field for every row (similar to:)
<input type ='submit' name='save[<?=$id;?>]' id='save' value='Save' />
and in the php code check witch key is set.
if(isset($_POST['save']) && is_array($_POST['save'])){
$id=key($_POST['save']);
}
You will need to replicate the bad thing for your comments as well but as a proof of concept you can run this snippet on phpfiddle.org
<?php
print_r($_POST);
if(isset($_POST['save']) && is_array($_POST['save'])){
echo key($_POST['save']);
}
?>
<html>
<form method='post'>
<input type='submit' name='save[1]' value='1' />
<input type='submit' name='save[2]' value='2' />
</form>
</html>
Wish i could provide you a really full answer but there's alot of work to be done on your code for it to be 'proper coding'. Again this becaome a matter of opinion beside the fact that your code is vunerable to sql injection and is NOT accepable.
Don't use your code at all for security vulnerability. Read more about sql injection Here. After all, For each row () create a form with a hidden input storing id of row .
I revised my code to make it work,create a nested table inside your td, so that tag will be accepted,
also see this link for a working reference,
HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr><td><table>
<form method="post" name="myform">
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
</form>
</table>
</td>
</tr>
<?php
}
?>
</table>

Delete From Table - Via Form

I have a HTML table that displays all my table entries. Also in the table is a delete button next to every SQL entry.
I want to be able to delete an entry the user selects. I've made the form to Post PHP_Self, and I'm passing in the index $i from the while loop as a reference:
$i = 0;
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<? echo $row['uniqueIdentifier']; ?>
</td>
<td>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type='hidden' name='remove_entrie_ID' value='<? echo $i; ?>' />
<input type='submit' value='Delete' name='remove_entrie'>
</form>
</td>
</tr>
<?
$i++;
}
So this is passed to itself, I now want to do a DELETE WHERE 'INDEX OF TABLE' == $i, type thing? I don't even know if this is possible.
if(isset($_POST['remove_entrie'])){
$index = $_POST['remove_entrie_ID']
echo "Index: " . $index;
//mysqli_query($con, "DELETE FROM Users WHERE INDEX = '$index'");
}
I'm basically using the $i to pick out the index of how the table was loaded, and then using that to pick out which row I want to delete. But I have a feeling this can't be done?
I basically want to delete a row the user has selected from the table.
You don't need $i variable. Just make simple modification in your list:
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<? echo $row['uniqueIdentifier']; ?>
</td>
<td>
<form action="" method="post">
<input type="hidden" name="remove_entrie_ID" value="<? echo $row['uniqueIdentifier']; ?>" />
<input type="submit" value="Delete" name="remove_entrie">
</form>
</td>
</tr>
<?
}
It is also good idea to escape specials chars etc in your post variable to avoid sql injection.

Update Multiple rows at one time in PHP

I am trying to update multiple rows on submit of a form (in particular this one is the "hours" field.
I have it working but only one of the value updates vs all of them.
There is the possibility of having different values for each update.
The form code:
$query2 = "select * FROM work_hours WHERE formid = $formid ";
$result = $mysqli->query( $query2 );
$num_results = $result->num_rows;
if( $num_results > 0){
echo " <table border='0' align='center'>
<tr>
<td colspan='2' align='center'>
<strong> Time Away Break Down</strong>
</td>
</tr>
<tr>
<td align='center'>Date</td>
<td align='left'>Hours</td>
</tr>";
while( $row = $result->fetch_assoc() ){
extract($row);
echo " <tr>
<td class='hidden_sm' align='center'>
<input type='text' name='id' size='10' value='$id' class='dept' readonly style='width:30px;'>
<input type='text' name='date' size='40' value='$date' class='dept' readonly> <input type='text' name='end_date' size='40' value='$end_date' class='dept' readonly>
</td>
<td class='hidden_sm' align='left' >
<input type='text' name='hours' size='10' style='width:30px;' value='$hours' class='dept' >
</td>
</tr>
";
}
echo "<tr>
<td colspan='2' align='center'>
<input type='submit' name='Submit' value='Submit Request'>
</td>
</tr>
</form>
</table>";//end table
Submit Code:
$id = $_POST['id'];
$formid = $_POST['formid'];
$hours = $_POST['hours'];
include 'connect-db.php';
$stmt = $mysqli->prepare("UPDATE work_hours SET hours = ? WHERE formid = ?");
$stmt->bind_param('si',
$_POST['hours'],
$_POST['formid']);
$stmt->execute();
if ( $stmt ) {
echo "<p align='center'>Thank you, this request has been approved.<BR>You will be redirected in 5 seconds</p>";
} else {
echo "Error, you status cannot be updated. <BR> Please contact your system administrator.";
}
$stmt->close();
?>
Could anyone point me in the right direction to have all values update on submit, as I have had zero luck.
As well I do understand the need to prevent SQL Injections, and that I am working, so no need to remind me.
Thanks in advance!
Looks like you'll want to use a CASE statement as explained here:
How does MySQL CASE work?
Use a loop to build the statement and you're better off using the id as the identifier instead of formid, since the id is the unique value and you could have different results in the form.

Adding to database with multiple text boxes

What I am trying to do with this script is allow users to update a url for their websites, and since each user isn't going to have the same amount of websites is is hard for me to just add $_POST['website'] for each of these.
Here is the script
<?php
include("config.php");
include("header.php");
include("functions.php");
if(!isset($_SESSION['username']) && !isset($_SESSION['password'])){
header("Location: pubs.php");
}
$getmember = mysql_query("SELECT * FROM `publishers` WHERE username = '".$_SESSION['username']."'");
$info = mysql_fetch_array($getmember);
$getsites = mysql_query("SELECT * FROM `websites` WHERE publisher = '".$info['username']."'");
$postback = $_POST['website'];
$webname = $_POST['webid'];
if($_POST['submit']){
foreach ( $_POST['website'] as $key => $value )
{
$update = mysql_query("UPDATE `websites` SET `postback` = '".mysql_real_escape_string($postback[$value])."' WHERE id = '$webname'");
}
}
print"
<div id='center'>
<span id='tools_lander'><a href='export.php'>Export Campaigns</a></span>
<div id='calendar_holder'>
<h3>Please define a postback for each of your websites below. The following variables should be used when creating your postback.<br />
cid = Campaign ID<br />
sid = Sub ID<br />
rate = Campaign Rate<br />
status = Status of Lead. 1 means payable 2 mean reversed<br />
A sample postback URL would be <br />
http://www.example.com/postback.php?cid=#cid&sid=#sid&rate=#rate&status=#status</h3>
<table class='balances' align='center'>
<form method='POST' action=''>";
while($website = mysql_fetch_array($getsites)){
print"
<tr>
<input type ='hidden' name='webid' value='".$website['id']."' />
<td style='font-weight:bold;'>".$website['name']."'s Postback:</td>
<td><input type='text' style='width:400px;' name='website[]' value='".$website['postback']."' /></td>
</tr>";
}
print"
<td style='float:right;position:relative;left:150px;'><input type='submit' name='submit' style='font-size:15px;height:30px;width:100px;' value='Submit' /></td>
</form>
</table>
</div>";
include("footer.php");
?>
What I am attempting to do insert the what is inputted in the text boxes to their corresponding websites, and I cannot think of any other way to do it, and this obviously does not works and returns a notice stating Array to string conversion
If there is a more logical way to do this please let me know.
UPDATE
I added a foreach statement, but this still doesn't seem to solve the problem. It doesn't update anything in the database.
I was able to fix the problem with some trial and error, Lawrence helped with the informing me to use a foreach statement. This is what I have ended up with.
<?php
include("config.php");
include("header.php");
include("functions.php");
if(!isset($_SESSION['username']) && !isset($_SESSION['password'])){
header("Location: pubs.php");
}
$getmember = mysql_query("SELECT * FROM `publishers` WHERE username = '".$_SESSION['username']."'");
$info = mysql_fetch_array($getmember);
$getsites = mysql_query("SELECT * FROM `websites` WHERE publisher = '".$info['username']."'");
$postback = $_POST['website'];
$webname = $_POST['webid'];
if($_POST['submit']){
$i = -1;
foreach ($postback as $key => $value)
{
$i ++;
print_r($webname[$i]);
$update = mysql_query("UPDATE `websites` SET `postback` = '".cleanQuery($postback[$key])."' WHERE `id` = '".$webname[$i]."'") or die("MySQL ERROR: ".mysql_error());
}
}
print"
<div id='center'>
<span id='tools_lander'><a href='export.php'>Export Campaigns</a></span>
<div id='calendar_holder'>
<h3>Please define a postback for each of your websites below. The following variables should be used when creating your postback.<br />
cid = Campaign ID<br />
sid = Sub ID<br />
rate = Campaign Rate<br />
status = Status of Lead. 1 means payable 2 mean reversed<br />
A sample postback URL would be <br />
http://www.example.com/postback.php?cid=#cid&sid=#sid&rate=#rate&status=#status</h3>
<table class='balances' align='center'>
<form method='POST' action=''>";
while($website = mysql_fetch_array($getsites)){
print"
<tr>
<input type ='hidden' name='webid[]' value='".$website['id']."' />
<td style='font-weight:bold;'>".$website['name']."'s Postback:</td>
<td><input type='text' style='width:400px;' name='website[]' value='".$website['postback']."' /></td>
</tr>";
}
print"
<td style='float:right;position:relative;left:150px;'><input type='submit' name='submit' style='font-size:15px;height:30px;width:100px;' value='Submit' /></td>
</form>
</table>
</div>";
include("footer.php");
?>

Update value in the database when done editing using PHP/jQuery/Ajax

I have a table something like this:
Product SellingPrice Cost Profit
Product 1 49 45 4
Product 2 54 50 4
When i put value in the profit column the sellingprice will calculate. I fetched the cost value from the database. I'm done working with the calculation using jQuery but I'm stuck on how to update it in the database. Could someone guide me about the server side implementation?
Here is my code:
<html>
<head>
<title>Content Management System</title>
<script>
//calculate the selling price
$(document).ready(function(){
$('tr').each(function(){
var result = 0;
$(this).find("input[name=cost],input[name=profit]").each(function(){
result += (+$(this).val());
});
$(this).find("input[name=sellingprice]").val(result).css("background-color", "green");
});
});
</script>
</head>
<body>
<table>
<tr>
<td><center>ID</center></td>
<td><center>Product</center></td>
<td><center>Selling Price</center></td>
<td><center>Current Cost</center></td>
<td><center>Profit</center></td>
</tr>
<?php
$result = mysql_query("SELECT id, product, cost FROM inventory");
while ($myrow = mysql_fetch_row($result))
{
?>
<tr>
<td>
<?php echo $myrow[0]; ?>
</td>
<td>
<?php echo $myrow[1]; ?>
</td>
<td>
<?php echo "<input type='text' name='sellingprice' size='10' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='cost' size='10' value='$myrow[2]' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='profit' size='10' />"; ?>
</td>
</tr>
<?php
}
?>
</table>
</center>
</body>
</html>
change your html and create a new php file to handle your form submission.
in php get the values through $_GET[""] and insert them into table.
<body>
<form name="some_name" id="form1" action="somephpfilename.php">
<table>
<tr>
<td><center>ID</center></td>
<td><center>Product</center></td>
<td><center>Selling Price</center></td>
<td><center>Current Cost</center></td>
<td><center>Profit</center></td>
</tr>
<?php
$result = mysql_query("SELECT id, product, cost FROM inventory");
while ($myrow = mysql_fetch_row($result))
{
?>
<tr>
<td>
<?php echo $myrow[0]; ?>
</td>
<td>
<?php echo $myrow[1]; ?>
</td>
<td>
<?php echo "<input type='text' name='sellingprice' size='10' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='cost' size='10' value='$myrow[2]' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='profit' size='10' />"; ?>
</td>
</tr>
<?php
}
?>
</table>
</center>
<input type="submit" name="update" value="update to db">
<form>
</body>
You add form tag to your table rows and when form is submitted, you grab / validate incoming data and run UPDATE query on your table by ids. Also, you need to change your input elements to use Arrays:
echo "<input type='text' name='sellingprice[".$myrow[0]."]' size='10' readonly='true'/>";
Something like that...

Categories