How can PHP scripts be structured to handle delete actions for specific records based on user input in a web application?
To handle delete actions for specific records based on user input in a web application, you can use a combination of PHP and SQL. You can pass the record ID to be deleted through a form submission or URL parameter, then use SQL DELETE query to remove the record from the database. It's important to validate and sanitize the user input to prevent SQL injection attacks.
<?php
// Check if the form is submitted
if(isset($_POST['delete_record'])){
// Get the record ID to be deleted
$record_id = $_POST['record_id'];
// Sanitize the input
$record_id = filter_var($record_id, FILTER_SANITIZE_NUMBER_INT);
// Connect to the database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute the SQL query to delete the record
$sql = "DELETE FROM records WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $record_id);
$stmt->execute();
// Close the connection
$stmt->close();
$conn->close();
// Redirect back to the page after deletion
header("Location: your_page.php");
exit();
}
?>
Related Questions
- Wie können Funktionsrestriktionen in PHP-Klassen implementiert werden, um sicherzustellen, dass bestimmte Methoden nur unter bestimmten Bedingungen ausgeführt werden können?
- What are some common methods for replacing placeholders in XML files using PHP?
- In what scenarios would it be more efficient to use a multi-step approach, like the one described in the forum thread, instead of a single regular expression pattern in PHP?