What is the best practice for deleting data from a MySQL database table using PHP?

When deleting data from a MySQL database table using PHP, it is best practice to use prepared statements to prevent SQL injection attacks. This involves using placeholders in the SQL query and binding the actual values to these placeholders before executing the query. This approach helps to sanitize user input and protect the database from malicious attacks.

<?php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

// Check if deletion was successful
if ($stmt->affected_rows > 0) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

// Close statement and connection
$stmt->close();
$conn->close();
?>