Add a delete button to a table populated from a database - php

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
}
}

Related

How to add a delete button in the html table to delete entire row from database? [duplicate]

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user from the MySQL table. I can't seem to get it to work though.
This is my code for the results page:
<?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If results
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
and, this is my delete.php script
<?php
//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//if it updated
?>
<strong>Contact Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
I cannot figure out why this is not working.
You have to pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?> (the name value) in a hidden field or pass this value in URL:
Replace
<td class="contact-delete">
<form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form>
</td>
With
<td class="contact-delete">
<form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
USe javascript
<input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="« Back" />
and in delet.php
$id=$_GET['id'];
and put $id in your sql statement.
You are missing to pass name in this line:
<input type="hidden" name="name" value="">
You need to have something (<?php echo $contact['name']; ?>) in the value attribute.
BTW, do not use deprecated mysql_* functions, use PDO or mysqli_* instead.
<input type="hidden" name="name" value="">
You are missing a value which wil be picked up by this line in your delete file.
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
Right now it isn't receiving anything, which is why it will not work.
So add a value to it and it will work. Example:
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
First, you should not write the code in that way; the code has no protection against SQL injection.
1. Try to use primary IDs instead of using a name (what happens if 2 people has the same name?).
So, you can create a hidden field to know which 'person' you are dealing with.
<input type="hidden" name="contact_id" value="<?php $contact['contact_id']; ?>">
2. Sanitize variables to avoid attacks:
<?php $contact_id = isset($_POST['contact_id'])?intval($_POST['contact_id']):0;
// proceed with the query
if($contact_id>0) { $query = "DELETE FROM contacts WHERE contact_id = '$contact_id'";
}
// redirect to the main table with header("location: main.php");
?>

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.

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.

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')");

How to add a delete button to a PHP form that will delete a row from a MySQL table

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user from the MySQL table. I can't seem to get it to work though.
This is my code for the results page:
<?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If results
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
and, this is my delete.php script
<?php
//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//if it updated
?>
<strong>Contact Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
I cannot figure out why this is not working.
You have to pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?> (the name value) in a hidden field or pass this value in URL:
Replace
<td class="contact-delete">
<form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form>
</td>
With
<td class="contact-delete">
<form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
USe javascript
<input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="« Back" />
and in delet.php
$id=$_GET['id'];
and put $id in your sql statement.
You are missing to pass name in this line:
<input type="hidden" name="name" value="">
You need to have something (<?php echo $contact['name']; ?>) in the value attribute.
BTW, do not use deprecated mysql_* functions, use PDO or mysqli_* instead.
<input type="hidden" name="name" value="">
You are missing a value which wil be picked up by this line in your delete file.
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
Right now it isn't receiving anything, which is why it will not work.
So add a value to it and it will work. Example:
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
First, you should not write the code in that way; the code has no protection against SQL injection.
1. Try to use primary IDs instead of using a name (what happens if 2 people has the same name?).
So, you can create a hidden field to know which 'person' you are dealing with.
<input type="hidden" name="contact_id" value="<?php $contact['contact_id']; ?>">
2. Sanitize variables to avoid attacks:
<?php $contact_id = isset($_POST['contact_id'])?intval($_POST['contact_id']):0;
// proceed with the query
if($contact_id>0) { $query = "DELETE FROM contacts WHERE contact_id = '$contact_id'";
}
// redirect to the main table with header("location: main.php");
?>

Categories