What are the advantages of using prepared statements over traditional SQL queries in PHP for database operations?

Prepared statements offer several advantages over traditional SQL queries in PHP for database operations. They help prevent SQL injection attacks by separating SQL code from user input, improve performance by allowing the database to optimize the query execution plan, and make it easier to reuse queries with different parameters.

// Using prepared statements to safely execute a query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();