What are the advantages of using prepared statements in PHP for preventing SQL injection attacks?

SQL injection attacks occur when malicious SQL statements are inserted into input fields on a website, allowing attackers to manipulate the database. One way to prevent SQL injection attacks in PHP is to use prepared statements. Prepared statements separate SQL code from user input, preventing attackers from injecting malicious code into the query. This method parameterizes the SQL query, allowing the database to distinguish between code and data.

// Using prepared statements to prevent SQL injection attacks
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");

// Prepare a SQL query with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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