Why last row deleted when refresh page in wordpress - php

When I refresh page table row deleted and last query deleted when I click on any delete button of other row. Why is this happened?
This is table which I displayed
<?php
global $wpdb;
$table= 'wp_contact_form';
$result = $wpdb->get_results ( "SELECT * FROM $table" );
if(!empty($result)){
foreach ( $result as $print ) {
?>
<tr>
<td><?php echo $print->id;?></td>
<td><?php echo $print->names;?></td>
<td><?php echo $print->emails;?></td>
<td><?php echo $print->gender;?></td>
<td><?php echo $print->age;?></td>
<td><input type="submit" value="Edit" id="" name="update"></td>
<td><input type="submit" value="delete" id="delete" name="delete"></td>
</tr>
<?php
}
}
?>
this is delete query
$id= $print->id;
if(isset($_POST['delete']))
{
$result = $wpdb->delete($table, array('id' => $id));
if(!empty($result))
{
echo "success";
}
}
error screenshot - https://prnt.sc/wdg3xv

You're not specifying which ID should be deleted if $_POST['delete'] is set, right now you're asking WP to just delete something.
You need to wrap your elements in a form and add a field that contains the exact ID of the element you want to delete, like this:
<td>
<input type="submit" name="delete" value="delete" />
<input type="hidden" name="targetItem" value="<?php echo $print->id;?>" />
</td>
Then in your PHP use that field's ID to delete it from the DB:
if (isset($_POST['delete']))
$result = $wpdb->delete($table, array('id' => $_POST['targetItem']));

Related

Add a delete button to a table populated from a database

I have a table which I populate from a mysql db. I want to add a delete button to each of the rows in the table, and when the button is clicked, I want to remove that line from the db table. I am using an array to update any changes made to the table. How can I use that array to delete a specific row too?
<table>
<tr><th>Category ID</th><th>Description</th><th>Valid</th><th></th></tr>
<?php
$query=mysqli_query($link,"SELECT * FROM cd_categories");
while($row = mysqli_fetch_array($query)){
$catid = $row['Catg_Id'];
$des = $row['Description'];
$datep = $row['Date_Posted'];
$postedb = $row['Posted_By'];
$valid = $row['Valid_YN'];
?>
<tr><td><input type="text" name="data[<?php echo $catid; ?>][catid]" value="<?php echo $catid; ?>" ></td>
<td><input type="text" name="data[<?php echo $catid; ?>][des]" value="<?php echo $des; ?>" ></td>
<td><input type="button" name="data[<?php echo $catid; ?>][delete]" value="Delete" ></td>
</tr>
<?php } ?>
</table>
<br>
<input type="submit" name="update" value="Save Changes" >
To remove a row from database you need to use a DELETE statement with a primary key, which you need to pass from this while loop.
Make a link inside while loop: [Demo]
<a href='delete.php?id=your_id'>Delete</a>
Now in your delete page, you need to capture or store the id using $_GET and using the DELETE Statement you can simply delete row from database.
DELETE FROM table_name WHERE primary_key=your_get_value;
Note: In your delete page just make a query for delete the row also
make some security.
Try this approach:
<table>
<tr><th>Category ID</th><th>Description</th><th>Valid</th><th></th></tr>
<?php
$query=mysqli_query($link,"SELECT * FROM cd_categories");
while($row = mysqli_fetch_array($query)){
$catid = $row['Catg_Id'];
$des = $row['Description'];
$datep = $row['Date_Posted'];
$postedb = $row['Posted_By'];
$valid = $row['Valid_YN'];
?>
<tr><td><input type="text" name="catid_<?php echo $catid; ?>" value="<?php echo $catid; ?>" ></td>
<td><input type="text" name="desc_<?php echo $catid; ?>" value="<?php echo $des; ?>" ></td>
<td>
Edit |
Delete</td>
</tr>
<?php } ?>
</table>
<br>
in delete.php:
delete from table where cat_id= $_GET["id"];
in edit.php
$desc =
update table set desc=$_GET["desc_".$_GET["id"]], catid = $_GET["catid_".$_GET["id"]] where cat_id= $_GET["id"];
Basically, to do this without javascript, you need to have a separate form for each row of your HTML table (which displays one row from your db). Add a hidden input field in your form which contains the unique identifier for that particular row, and a submit button to delete the row. Leave the form action field blank so the same page receives the submitted form data, then have PHP test for which button was submitted and if it was the delete button, delete the data and re-display the table.
Example HTML code:
<table>
<tr><td>
<form action="" method="post">
<input type="hidden" name="row_id" value="<?php echo 'identifier here'; ?>">
<?php echo 'stuff here'; ?>
<input type="submit" name="submit" value="Save Changes">
<input type="submit" name="submit" value="Delete">
</form>
</td></tr>
</table>
Example PHP code:
if (isset($_POST['submit')) // Form submitted
{
if ($_POST['submit'] == 'Delete') // Delete button clicked
{
// Run delete query based on the hidden field containing the row identifier
}
elseif ($_POST['submit'] == 'Save Changes')
{
// Run update query
}
}

Form action not allowing the delete of a record

I had to add a form action to go to a different page to edit a specific record, but with doing that, it won't allow me to delete a record because it is taking me away from it before it will do the query. I am unsure of how to make this work and still get to the new page when I hit the "Edit" button.
<table id="tableid">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Product</th>
<th>Save</th>
<th>Delete</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$stmt = $dbc->query("SELECT `id`,`first`,`last`,`product` FROM users");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
?>
<form method="POST" action="edit-product">
<tr>
<td><?php echo $row['id'];?>"</td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<input name="id" type="hidden" value="<?php echo $row['id'];?>" readonly>
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<td><input name="save" type="submit" value="Save"></td>
<td><div class="delete-class" name="delete" id="<?php echo $row['id']; ?>">Delete</div></td>
<td><input name="edit" type="submit" value="Edit"></td>
</tr>
</form>
<?php } ?>
</tbody>
</table>
PHP DELETE query
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
How can I change the markup to still get both the edit (going to another page with the action) and the delete to work on this page?
UPDATE AJAX code:
$(function() {
$(".delete_class").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete-product.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // DO SOMETHING
} else { // DO SOMETHING }
}
)); //here
});
});
This is not very ideal but one way to do it. You change the HTML markup to create two forms, one for edit case and another one for Delete. The delete case sends the request to the current page like this:
while($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<td>
<form method="post" action="edit-product">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<input name="save" type="submit" value="Edit">
</form>
</td>
<td>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="delete" type="submit" value="Delete">
</form>
</td>
</tr>
<?php }
?>
</tbody>
</table>
<?php
// the delete code goes here
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
I left out the save case but it will be similar to edit case.
Rather than having a form you could just have links instead of form submit buttons. That way each link could take you to a specific page that performs a specific task. By passing query string variables and using $_GET rather than $_POST, you can retain the product ID information.
Example:
<td>Save</td>
<td>Delete</td>
<td>Edit</td>
These individual pages could then perform your tasks in the database. Both save and delete could use Header re-directs to get back to your original page with your product list.
delete_product.php Example:
// delete product from database
$id = $_GET['id']; // Note that it's a $_GET
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
// re-direct to original list page
header("Location: product_list.php"); // or whatever you have your list page named.
The edit_product.php page would then have your typical form for making changes to a specific product. You will need to lookup the product again in the database using $_GET['id'] value to match it with.
As it was suggested in the comments, using AJAX would make the whole process appear to be seamless, rather than jumping around between pages and being re-directed.

Button to delete row from table - PHP SQL

I have a web page that outputs data from my sql database. Each row has a delete button that should delete the data in this particular row. I am having a issue where when I click the delete button it always deletes the row with the first/lowest ID regardless of which button I click. It doesnt delete the row I want it to delete. Here is my code:
HTML
<form action="process.php" method="post">
<?php
$sql = "
SELECT *
FROM playerTeam
";
$result = mysqli_query($connection, $sql);
?>
<table>
<?php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><input type="text" name="id" value="<?php echo $row['id']?>"></td>
<td><input type="text" name="fName[]" value="<?php echo $row['firstName']?>"></td>
<td><input type="text" name="sName[]" value="<?php echo $row['surName']?>"></td>
<td><input type="text" name="team[]" value="<?php echo $row['team']?>"></td>
<td><input type="submit" name="delete" value="Delete"></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
<?php
}
}
?>
</table>
</form>
process.php
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$sql = "DELETE FROM playerTeam WHERE id='$id'";
if (mysqli_query($connection, $sql)) {
echo "Record deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
please could someone help me. Thanks
Because you delete the value of last id in
$id = $_POST['id'];
$sql = "DELETE FROM playerTeam WHERE id='$id'";
the value of $_POST['id'] is equal to last row in <?php echo $row['id']?>
in each run of the while the $_POST['id'] value replaced by new $row['id'] so the last on would be read in $_POST['id']
As you are using while($row = mysqli_fetch_assoc($result)), this will loop to the last row in your MySQL Table, thus every time, it will have the last id of your table.
You can code it in a way that your delete script will get the id. So, your delete button for each row will be have the row id, e.g. process.php?1, process.php?2, process.php?3 and so on.
tablepage.php (not sure of your page's real name)
Replace this line:
<td><input type="submit" name="delete" value="Delete"></td>
With this:
<td><p><a href="/process.php?id=<?php echo $id; ?>"></td>
process.php?id=1
// this will get `id=1` and thus your `id` will be `1`, and it will delete row `1`.
$id = $_GET['id'];
$sql = "DELETE FROM playerTeam WHERE id='$id'";
if (mysqli_query($connection, $sql)) {
echo "Record deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
Hope that helps, thanks!
In actual in this condition ,use ajax and jquery is much more easier i think .But do only by php gonna be use logic code
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><input type="text" name="id_<?= $i ?>" value="<?php echo $row['id']?>"></td>
<td><input type="text" name="fName[]" value="<?php echo $row['firstName']?>"></td>
<td><input type="text" name="sName[]" value="<?php echo $row['surName']?>"></td>
<td><input type="text" name="team[]" value="<?php echo $row['team']?>"></td>
<td><input type="submit" name="delete[<?= $i ?>]" value="Delete"></td>
<td><input type="submit" name="update[<?= $i ?>]" value="Update"></td>
</tr>
<?php
$i++; //for unique num for each row
}
process.php
if (isset($_POST['delete'])){
$delete_id = array_keys($_POST['delete']);//print array key as a array
$delete_id = $delete_id[0];//so get array key
$id = $_POST["id_$delete_id"];//get its relative id
.....
}

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