How can prepared statements in PHP prevent SQL injections?

Prepared statements in PHP prevent SQL injections by separating SQL logic 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. Prepared statements also automatically handle escaping special characters, further reducing the risk of SQL injection attacks.

// 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 statement
$stmt->execute();

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