updating mysql database after an entry is deleted - php

Working on deleting an entry from my database table.
Currently the delete is working. However it deletes the "id + 1"
My script populates a "delete " button right next to an entry populated from mysql table.
When I hit delete next to an entry, it deletes the item +1.
I think it has to do with the while loop, the way I populate items.
Any ideas on how to fix this?
<?php
while($row = mysqli_fetch_array($result)) : ?>
<tr>
</table border = '1'><br><table border = '1'><th>Subject</th><th>Sender</th> <th>Message</th><th>Delete</th>
<?php
echo "<tr><td>";
echo $row['subject'];
echo "<td>";
echo $row['sender'];
echo "<td>";
echo $row['msgText'];
echo "<td>";
?>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php $_SESSION['id'] = $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</tr>
<?php endwhile; ?>
here is the script in delete.php
<?php
session_start();
$id = $_SESSION['id'];
$con=mysqli_connect("localhost","root","","something");
$sql = "DELETE FROM `mailbox` WHERE `id`= '$id'";
$result = mysqli_query($con,$sql);
header('Location: loggedin.php');
?>

<input type="hidden" name="delete_id" value="<?php $_SESSION['id'] = $row['id']; ?>" />
change it to:
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" />
and in your delete.php, simply replace $_SESSION['id'] to $_POST['delete_id']
P/S: By the way, you've forgot to add session_start(); in your form's php, if you do really want to use it, but not a good idea for this time.

The $_SESSION['id'] gets overridden each time in the loop.
Why not just simply use $_POST["delete_id"] to retrieve row id.

Your Table Structure is wrong
<?php
while($row = mysqli_fetch_array($result)) :
?>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Message</th>
<th>Delete</th>
</tr>
<tr>
<?php
echo "<td>";
echo $row['subject'];
echo "</td><td>";
echo $row['sender'];
echo "</td><td>";
echo $row['msgText'];
echo "</td>";
?>
<td>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php $_SESSION['id'] = $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
also don't use $_SESSION['id'] while deleting the records. use $_POST['delete_id']

Related

How to delete specified row in a database table using post method in php

//Deleting is working. However, I can't delete the specified row in the table. It always deletes the last row. I hope you could help me. Thank you! This is my code for displaying data from database:
<form action="deleteCart.php" method = "post" role="form">
<?php
while ($row = mysqli_fetch_array($result2)) {
?>
<tr style="text-align: center;">
<td> <img src="images/<?php echo $row["ImageProduct1"]; ?>"/>
<td><?php echo $row['NameProduct1']; ?> </td>
<td>#<?php echo $row['OrderID']; ?></td>
<td><?php echo $row['OrderQuantity']; ?></td>
<td><input type="submit" name="cancelOrder" value = "Cancel" ></td>
<td><input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>"></td>
</tr>
<?php
}
?>
</form>
//This is my code for deleting:
if(isset($_POST['cancelOrder'])){
orderID = $_POST['hiddenID'];
mysqli_query($con, "DELETE FROM OrderTable WHERE OrderID=$_POST[hiddenID];");
header('location: deleteCart.php');
}
Delete only the last record because you submitting form whole table record. you should try this code. it will work fine.
this will submit separate record.
<?php
while ($row = mysqli_fetch_array($result2)) {
?>
<form action="deleteCart.php" method = "post" role="form">
<tr style="text-align: center;">
<td><img src="images/<?php echo $row["ImageProduct1"]; ?>"/>
<td><?php echo $row['NameProduct1']; ?> </td>
<td>#<?php echo $row['OrderID']; ?></td>
<td><?php echo $row['OrderQuantity']; ?></td>
<td>
<input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>">
<input type="submit" name="cancelOrder" value = "Cancel" >
</td>
</tr>
</form>
<?php
}
?>

Edit links in table not connecting to mysql

I am having an issue editing mysql database through a html table.
when I run a simple while loop it works, I can pull in the data and update the database:
Working Code
<?php
while ($row = mysqli_fetch_array($res))
echo "$row[id]. $row[Key_Role] .$row[Incumbant] .$row[Attrition_Risk] .$row[Ready_Now] .$row[lowerYears] .$row[higherYears]<a href='edit.php?edit=$row[id]'>edit</a> <br />";
?>
However, when I run the php through a table, the edit links no longer pull in the data from mysql and I am not able to update information. I have put below the index and edit php files.
Index.php
<?php
include_once('db.php');
if(ISSET($_POST['Key_Role']))
{
$Key_Role = $_POST['Key_Role'];
$Incumbant = $_POST['Incumbant'];
$Attrition_Risk = $_POST['Attrition_Risk'];
$Ready_Now = $_POST['Ready_Now'];
$lowerYears = $_POST['1-2_Years'];
$higherYears = $_POST['3-5_Years'];
$sql = "INSERT INTO tmdata VALUES('','$Key_Role','$Incumbant','$Attrition_Risk','$Ready_Now','$lowerYears','$higherYears')";
$res = mysqli_query($conn, $sql);
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
if ($res)
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
else
echo "Failed";
} else {
echo "please enter a key Role";
}
$res = mysqli_query($conn, "SELECT * FROM tmdata");
?>
<style>
<?php include 'style.css' ?>
</style>
<H1 class="Title">Talent Management System</H1>
<form action="." method="post">
Key Role:<input type="text" name="Key_Role">
Incumbant:<input type="text" name="Incumbant">
Attrition_Risk:<input type="text" name="Attrition_Risk">
Ready_Now:<input type="text" name="Ready_Now">
1-2_Years:<input type="text" name="1-2_Years">
3-5_Years:<input type="text" name="3-5_Years">
<input type ="submit" value="Enter">
</form>
<h1> List Of Key Roles</h1>
<?php
/*
while ($row = mysqli_fetch_array($res))
echo "$row[id]. $row[Key_Role] .$row[Incumbant] .$row[Attrition_Risk] .$row[Ready_Now] .$row[lowerYears] .$row[higherYears]<a href='edit.php?edit=$row[id]'>edit</a> <br />";
*/
?>
<table>
<tr>
<th>id</th>
<th>Key_Role</th>
<th>Incumbant</th>
<th>Attrition_Risk</th>
<th>Ready_Now</th>
<th>1-2_Years</th>
<th>3-5_Years</th>
<th>Edit</th>
</tr>
<?php while ($row = mysqli_fetch_array($res)):;?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['Key_Role'];?></td>
<td><?php echo $row['Incumbant'];?></td>
<td><?php echo $row['Attrition_Risk'];?></td>
<td><?php echo $row['Ready_Now'];?></td>
<td><?php echo $row['lowerYears'];?></td>
<td><?php echo $row['higherYears'];?></td>
<td><a href='edit.php?edit=$row["id"]'>edit</a></td>
</tr>
<?php endwhile;?>
</table>
Edit.php
<?php
include_once('db.php');
if (isset($_GET["edit"]))
{
$id = $_GET["edit"];
$res = mysqli_query($conn, "SELECT * FROM tmdata WHERE id='".$id."'");
$row = mysqli_fetch_array($res);
}
if( isset($_POST['newKey_Role']) || isset($_POST['newIncumbant']) || isset($_POST['newAttrition_Risk']) || isset($_POST['newReady_Now']) || isset($_POST['newLowerYears']) || isset($_POST['newHigherYears']) )
{
$newKey_Role = $_POST['newKey_Role'];
$newIncumbant = $_POST['newIncumbant'];
$newAttrition_Risk = $_POST['newAttrition_Risk'];
$newReady_Now = $_POST['newReady_Now'];
$newLowerYears = $_POST['newLowerYears'];
$newHigherYears = $_POST['newHigherYears'];
$id = $_POST['id'];
$sql = "UPDATE tmdata SET Key_Role='$newKey_Role', Incumbant='$newIncumbant', Attrition_Risk='$newAttrition_Risk', Ready_Now='$newReady_Now', lowerYears='$newLowerYears', higherYears='$newHigherYears' WHERE id='".$id."'";
$res = mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
<form action="edit.php" method="post">
Key Role:<input type="text" name="newKey_Role" value ="<?php echo $row[1]; ?>"></input> <br />
Incumbant:<input type="text" name="newIncumbant" value ="<?php echo $row[2]; ?>"></input> <br />
Attrition_Risk:<input type="text" name="newAttrition_Risk" value ="<?php echo $row[3]; ?>"></input> <br />
Ready_Now:<input type="text" name="newReady_Now" value ="<?php echo $row[4]; ?>"></input> <br />
1-2 Years:<input type="text" name="newLowerYears" value ="<?php echo $row[5]; ?>"></input> <br />
3-5 Years:<input type="text" name="newHigherYears" value ="<?php echo $row[6]; ?>"></input> <br />
<input type="hidden" name="id" value ="<?php echo $row[0]; ?>">
<input type ="submit" value="Update">
</form>
<style>
<?php include 'style.css' ?>
</style>
It looks as though the ID is not pulling across to the edit php. I also tried manually inputting the id in the table:
<td><a href='edit.php?edit=$row[184]'>edit</a></td>
but this also did not work.
Any help would be very much appreciated.
Thank you in advance.
I figured out that you need to put the link in php.
<td><?php echo "<a href='edit.php?edit=$row[id]'>edit</a>"?></td>
That worked in the end.

Insert to database when the button is click

im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");

Delete multiple rows mysql with checkbox

please help in deleting multiple rows from a table.
home.php
<form action="del.php" method="get" enctype="multipart/form-data">
<?php
while($row=mysql_fetch_array($rs))
{
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<?php echo $row['id']; ?>]" type="checkbox" id="checkbox[<?php echo $row['id']; ?>]" value="<?php echo $row['id']; ?>"></td>
<td><?php echo $row['listingtype'];?></td>
<td><?php echo $row['propertyname'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['listdate'];?></td>
</tr>
<?php
}
?>
</table>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr></form>
del.php
<?php
include "include/db.php";
$tbl_name='propertylistingbasicinfo';
// Check if delete button active, start this
if ( ! empty($_POST['delete'])) {
foreach ($_POST['need_delete'] as $id => $value) {
$sql = 'DELETE FROM `'.$tbl_name.'` WHERE `id`='.(int)$id;
mysql_query($sql);
}
header('Location: home.php');
}
?>
Error : When i click on delete button, blank screen come.
And url looks like this : http://localhost/realestate/del.php?need_delete%5B2%5D=2&delete=Delete
your mixing up GET with POST, change form method to post
You need something similar to this in your form
<input type="checkbox" name="record[]" value="<?php echo $id ?>">
then you can use implode() function to concatenate ids and remove them
$deleted = implode(',',$_POST['record']);
$query = mysql_query("delete from table where id in ('$deleted') ");
Not tested but this the idea.
The problem is that you are submitting the form with method="get" and in del.php, you are accessing values from $_POST. Change method="get" to method="post" on home.php
I would change it to the following...
home.php:
<form action="del.php" method="post" enctype="multipart/form-data">
<table>
<?php while($row=mysql_fetch_array($rs)) { ?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="need_delete[]" value="<?php echo $row['id']; ?>" type="checkbox" id="checkbox[<?php echo $row['id']; ?>]" />
</td>
<td><?php echo $row['listingtype'];?></td>
<td><?php echo $row['propertyname'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['listdate'];?></td>
</tr>
<?php } ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete" />
</td>
</tr>
</table>
del.php:
<?php
//Get the db-file and set the table name
include "include/db.php";
$tbl_name='propertylistingbasicinfo';
// Check if delete button active, start this
if ( !empty($_POST['delete'])) {
//Let's sanitize it
$sanitized_post_ids = array();
foreach($_POST['need_delete'] as $id ) $sanitized_post_ids[] = intval($id);
//Get the ids and add a trailing ",", but remove the last one
$in_str = substr(implode(',', $sanitized_post_ids), 0, -1);
//Build the sql and execute it
$sql = 'DELETE FROM ' . $tbl_name ' WHERE id IN (' . $in_str . ')';
mysql_query($sql);
//Redirect!
header('Location: home.php');
}
?>
Hope this works out for you (and that I didn't manage to add a typo or similar misshaps)!

image button for deleting users from mysql

so I've got a problem
$query = "SELECT * FROM users;";
$result = mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['fio']; ?></td>
<td><?php echo $row['born_date']; ?></td>
<td><?php echo $row['address']; ?></td>
<td><?php echo $row['number']; ?></td>
<td><?php echo $row['work_post']; ?></td>
<td><?php echo $row['inwork_date']; ?></td>
<td><center><form action="delete.php" method="POST"><input type="hidden" name="user_id" value="'.$row['user_id'].'"><input type="Submit" class="deleteButton" value="Delete"></form></center></td>
</tr>
<?php
and in delete.php I have
<?php
if(isset($_POST['Submit'])) {
$query = "DELETE FROM users WHERE user_id='$user_id'";
$result = mysql_query($query) or die(mysql_error());
header("Location: edit.php");
exit;
}
?>
I see list of users - it works! But I can not delete anybody.
You're not correctly inserting the ID due to the fact that the PHP interpreter isn't "active" where you seem to think it is.
As such, change...
<input type="hidden" name="user_id" value="'.$row['user_id'].'">
...to...
<input type="hidden" name="user_id" value="<?php echo $row['user_id']; ?>">
...and all will be well. (It happens to us all occasionally.)
Incidentally, wrapping each delete link in a form is perhaps a bit excessive - is there a reason you don't want to use a "normal" link?
UPDATE
You'll also most likely need to explicitly use the HTTP post variable on your delete page as follows:
$query = "DELETE FROM users WHERE user_id='" . intval($_POST['user_id']) . "'";
<input type="Submit" class="deleteButton" value="Delete">
You need a name on this field to pass your if(isset($_POST['Submit'])) {
<input type="Submit" class="deleteButton" value="Delete" name="Submit">
On a slightly different note, I hope you are doing some sort of check that the user executing the delete call has permissions.

Categories