What are some best practices for using PHP to handle form submissions and database interactions in an online survey tool?

Issue: When handling form submissions and database interactions in an online survey tool using PHP, it is important to sanitize user input to prevent SQL injection attacks, validate form data to ensure it meets the required format, and securely store sensitive information in the database. PHP Code Snippet:

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "survey_db";

$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']);
$age = mysqli_real_escape_string($conn, $_POST['age']);

// Validate form data
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email format");
}

// Insert data into the database
$sql = "INSERT INTO survey_responses (name, email, age) VALUES ('$name', '$email', '$age')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>