What are the advantages of using prepared statements in PHP when working with databases?

When working with databases in PHP, using prepared statements is important for preventing SQL injection attacks. Prepared statements separate the SQL query from the user input, which helps to sanitize and escape input values automatically. This approach also improves performance by allowing the database to prepare the query once and execute it multiple times with different parameters.

// Using prepared statements in PHP to prevent SQL injection attacks

// Establish a database connection
$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 the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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