What best practices should be followed when using PHP to interact with databases and file systems for tasks like deletion?
When deleting files or records from a database using PHP, it is important to validate user input and sanitize any input to prevent SQL injection attacks. Additionally, always confirm the deletion action with the user before executing it to avoid accidental deletions. Lastly, make sure to handle any errors that may occur during the deletion process to provide a smooth user experience.
<?php
// Validate and sanitize user input
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
// Confirm deletion action with user
if (isset($_POST['delete'])) {
// Perform deletion from database
$query = "DELETE FROM table_name WHERE id = :id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Handle errors
if ($stmt->rowCount() > 0) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record.";
}
}
?>
Related Questions
- What are the best practices for storing session data in PHP, especially when comparing it with database values?
- Are there specific best practices for handling line breaks in text files when using PHP?
- How can PHP be used in conjunction with Ajax/jquery to create a countdown timer for a browser game quest?