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.";
    }
}
?>