How can PHP be used to implement "Delete" and "Edit" buttons next to a table on a website?
To implement "Delete" and "Edit" buttons next to a table on a website using PHP, you can create a form for each row in the table with hidden input fields containing the row's unique identifier. When the user clicks on the "Delete" button, the form can submit a POST request to a PHP script that handles the deletion. Similarly, when the user clicks on the "Edit" button, the form can submit a POST request to a PHP script that redirects to an edit page with the row's unique identifier in the URL parameters.
<!-- HTML code for the table with Delete and Edit buttons -->
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Action</th>
</tr>
<?php
// Assume $rows is an array of rows from a database query
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>
<form method='post' action='delete.php'>
<input type='hidden' name='id' value='" . $row['id'] . "'>
<button type='submit'>Delete</button>
</form>
<form method='post' action='edit.php'>
<input type='hidden' name='id' value='" . $row['id'] . "'>
<button type='submit'>Edit</button>
</form>
</td>";
echo "</tr>";
}
?>
</table>
Related Questions
- What are some common pitfalls when handling form submissions in PHP, especially when dealing with error messages like in the provided code snippet?
- What are some best practices for ensuring the security and reliability of PHP files executed via Cronjobs?
- Why is the IF statement not triggering as expected in the PHP code?