How can prepared statements in PDO help prevent SQL injection when writing user input to a database in PHP?

Prepared statements in PDO help prevent SQL injection by separating SQL query logic from user input data. This means that user input is treated as data and not as part of the SQL query itself, making it impossible for malicious SQL code to be injected. Prepared statements automatically sanitize user input, making it a secure way to interact with a database in PHP.

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

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

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

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