Add a Delete Button to a PHP Form to Remove Rows from a MySQL Table
You've encountered difficulties adding a delete option to a results page that retrieves data from a MySQL table. Let's delve into the code to understand the issue and provide a solution.
The PHP code retrieves contact information and displays it in an HTML table. The issue arises in the delete functionality. You aim to pass the name value of each contact to a separate form, "delete.php," where the corresponding row in the MySQL table will be deleted.
Incorrect Code:
<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>
The Problem:
The problem lies in the hidden field's empty value in the delete form:
<input type="hidden" name="name" value="">
To delete the correct row, it's crucial to pass the name value associated with the contact you want to remove.
The Solution:
There are two ways to resolve this issue:
Method 1: Pass the name value in a hidden field
Replace the incorrect code with:
<td class="contact-delete"> <form action='delete.php' method="post"> <input type="hidden" name="name" value="<?php echo $contact['name']; ?>"> <input type="submit" name="submit" value="Delete"> </form> </td>
In this updated code, the hidden field's value is set to the contact's name. When the form is submitted, this value will be passed to "delete.php" and used to identify the row to be deleted.
Method 2: Pass the name value in the URL
Alternatively, you can use the URL to pass the name value:
Replace the incorrect code 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>
This code will pass the name value as a query string in the URL. In "delete.php," you can retrieve the value using $_GET['name'].
The above is the detailed content of How to Implement a Delete Button in a PHP Form to Remove Rows from a MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!