What are the advantages of using prepared statements in PHP when executing database queries?

When executing database queries in PHP, using prepared statements is advantageous because it helps prevent SQL injection attacks by separating SQL logic from user input. Prepared statements also improve performance as the database can optimize the query execution plan. Additionally, prepared statements make it easier to reuse query templates with different parameters.

// Using prepared statements to execute a database query in PHP

// Create a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a placeholder for the parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the parameter to the placeholder
$stmt->bindParam(':username', $username);

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

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