What are best practices for handling form data and inserting it into a database in PHP?

When handling form data in PHP and inserting it into a database, it is important to sanitize the data to prevent SQL injection attacks. One common method is to use prepared statements with parameterized queries to securely insert the data into the database. Additionally, it is recommended to validate the form data before inserting it to ensure that it meets the required format and constraints.

// 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 and validate form data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

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

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

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