What are the best practices for integrating PHP with HTML forms and databases for data storage?

When integrating PHP with HTML forms and databases for data storage, it is important to properly sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements when interacting with the database can help prevent against SQL injection vulnerabilities. Lastly, validating user input on the server-side before processing and storing it in the database is crucial for data integrity.

<?php
// Establish a 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 statement
$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: " . $stmt->error;
}

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