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

Prepared statements in PHP offer several advantages over traditional SQL queries, such as preventing SQL injection attacks by automatically escaping input variables, improving performance by allowing the database to compile the query only once and execute it multiple times with different parameters, and enhancing readability and maintainability of the code by separating the query logic from the data.

// Using prepared statements to prevent SQL injection
$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', $username);

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

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