What are best practices for creating a form in PHP that submits data to a MySQL database for querying?

When creating a form in PHP that submits data to a MySQL database for querying, it is important to sanitize user input to prevent SQL injection attacks. One best practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, validate user input on the server-side to ensure data integrity before inserting it into the database.

<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

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

// Prepare and bind the SQL statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

// Execute the statement
$stmt->execute();

echo "New record created successfully";

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