What are the best practices for securely passing and processing data from a form submission to delete a specific record from a database in PHP?

When deleting a specific record from a database in PHP, it is important to securely pass and process the data from a form submission to prevent SQL injection attacks. One best practice is to use prepared statements with parameterized queries to sanitize and validate the input data before executing the delete operation.

<?php
// Connect to the database
$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);
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize input data
    $record_id = $_POST['record_id']; // Assuming 'record_id' is the input field name
    $record_id = mysqli_real_escape_string($conn, $record_id);

    // Prepare and execute the delete query using a prepared statement
    $stmt = $conn->prepare("DELETE FROM table_name WHERE id = ?");
    $stmt->bind_param("i", $record_id); // Assuming 'id' is the column name
    $stmt->execute();

    // Check if the delete operation was successful
    if ($stmt->affected_rows > 0) {
        echo "Record deleted successfully";
    } else {
        echo "Error deleting record";
    }

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