How can prepared statements help prevent SQL injection in PHP?

Prepared statements in PHP help prevent SQL injection by separating SQL code from user input. This means that user input is treated as data rather than executable code, making it impossible for malicious SQL code to be injected into the query.

// Using prepared statements to prevent SQL injection in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

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

// Execute the query
$stmt->execute();

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