How can prepared statements in PHP prevent SQL injection attacks and enhance database security?

Prepared statements in PHP can prevent SQL injection attacks by separating SQL code from user input. This means that user input is treated as data rather than executable code, reducing the risk of malicious SQL injection. By using prepared statements, the database engine can distinguish between SQL code and data, enhancing database security.

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

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(array('username' => $username, 'password' => $password));

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