How can prepared statements in PDO be properly implemented to prevent SQL injection?

To prevent SQL injection when using PDO, it is crucial to use prepared statements. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed. To properly implement prepared statements in PDO, use placeholders in the SQL query and bind the user input values to these placeholders before execution.

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

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

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

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

// Fetch the results
$results = $stmt->fetchAll();