How can error handling be improved when executing a DELETE query in PHP to ensure successful deletion of database entries?

When executing a DELETE query in PHP, error handling can be improved by checking if the query was successful and displaying an error message if it fails. This can be achieved by using the mysqli_error() function to capture any errors returned by the database. Additionally, using prepared statements can help prevent SQL injection attacks and improve the overall security of the query.

// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Prepare and execute the DELETE query
$stmt = $connection->prepare("DELETE FROM table_name WHERE id = ?");
$stmt->bind_param("i", $id);

if ($stmt->execute()) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . mysqli_error($connection);
}

// Close the connection
mysqli_close($connection);