What are some best practices for handling form data insertion and retrieval in PHP to ensure data integrity and security?

When handling form data insertion and retrieval in PHP, it is important to sanitize user input to prevent SQL injection attacks and validate data to ensure data integrity. Use prepared statements with parameterized queries to prevent SQL injection vulnerabilities. Additionally, implement proper error handling and validation to ensure that only valid data is inserted into the database.

// Example of handling form data insertion using prepared statements
$conn = new mysqli($servername, $username, $password, $dbname);

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

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

// Set parameters and execute
$username = $_POST['username'];
$email = $_POST['email'];
$stmt->execute();

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