What are some best practices for handling data insertion and updates in PHP scripts to avoid errors and ensure proper functionality?

When handling data insertion and updates in PHP scripts, it is important to properly sanitize user input to prevent SQL injection attacks and ensure data integrity. Using prepared statements with parameterized queries can help prevent SQL injection and ensure proper handling of user input.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with placeholders for user input
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);

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