What are some best practices for connecting a form to a MySQL command in PHP?

When connecting a form to a MySQL command in PHP, it is essential to sanitize the input data to prevent SQL injection attacks. One best practice is to use prepared statements to securely execute SQL queries with user input. Additionally, validating and sanitizing the form data before executing the query can help ensure data integrity.

<?php
// Establish a connection to the MySQL 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);
}

// Sanitize form input data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

// Prepare and execute the SQL query using prepared statements
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

if ($stmt->execute()) {
    echo "New record created successfully";
} else {
    echo "Error: " . $conn->error;
}

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