What are the advantages of using PDO prepared statements over mysqli_real_escape_string for SQL injection prevention in PHP?

SQL injection is a common security vulnerability in web applications where malicious SQL queries are inserted into input fields. Using PDO prepared statements is a more secure way to prevent SQL injection compared to mysqli_real_escape_string. Prepared statements separate the SQL query from the user input, preventing attackers from injecting malicious code into the query.

// Using PDO prepared statements for SQL injection prevention
$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', $_POST['username']);

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

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