What are the best practices for structuring PHP code to handle database deletion queries?

When handling database deletion queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. It is also recommended to check for errors and handle exceptions properly to maintain the stability of the application. Additionally, it is good practice to sanitize user input before executing the deletion query.

<?php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

// Prepare the deletion query
$stmt = $pdo->prepare("DELETE FROM table WHERE id = :id");

// Sanitize user input
$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);

// Bind the parameter and execute the query
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

// Check for errors and handle exceptions
if($stmt->rowCount() > 0){
    echo "Record deleted successfully";
} else {
    echo "No records deleted";
}
?>