What are some best practices for securely inserting data into a database using PHP, especially when dealing with user input?

When inserting user input into a database using PHP, it is crucial to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL code from user input, making it impossible for malicious input to alter the SQL query. Additionally, input should be sanitized and validated before insertion to ensure data integrity and security.

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

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

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

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