What are some best practices for handling form submissions in PHP to ensure data is properly inserted into a database?

When handling form submissions in PHP to insert data into a database, it is important to sanitize user input to prevent SQL injection attacks. Additionally, validate the data to ensure it meets the required format before inserting it into the database. Use prepared statements to securely insert the data into the database and handle any potential errors that may occur during the insertion process.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

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

// Insert data into the database using prepared statements
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

if ($stmt->execute()) {
    echo "New record inserted successfully";
} else {
    echo "Error: " . $conn->error;
}

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