Are there any best practices for integrating forms with database connections in PHP?

When integrating forms with database connections in PHP, it is important to sanitize user input to prevent SQL injection attacks. One best practice is to use prepared statements to safely execute SQL queries with user input. Additionally, validating user input before inserting it into the database can help maintain data integrity.

<?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);
}

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

// Prepare and execute SQL query
$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;
}

$stmt->close();
$conn->close();
?>