How can prepared statements be utilized to enhance security when interacting with a database in PHP?

When interacting with a database in PHP, using prepared statements is crucial for enhancing security. Prepared statements help prevent SQL injection attacks by separating SQL code from user input. This means that user input is treated as data rather than executable code, making it much harder for attackers to manipulate the SQL query.

// Establish a database connection
$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 parameters to the placeholders
$stmt->bindParam(':username', $username);

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

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