How can prepared statements be utilized in PHP, specifically with PDO, to improve security when interacting with a SQL database?

Using prepared statements in PHP with PDO can improve security when interacting with a SQL database by separating SQL code from user input. This prevents SQL injection attacks by treating user input as data rather than executable code. Prepared statements also allow for the reuse of query templates, which can improve performance.

// Connect 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("SELECT * FROM users WHERE username = :username");

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

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

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