What are the advantages of using PDO over mysql_real_escape_string for database interactions in PHP?

Using PDO over mysql_real_escape_string for database interactions in PHP offers several advantages. PDO provides a more secure and reliable way to interact with databases by using prepared statements, which help prevent SQL injection attacks. Additionally, PDO supports multiple database drivers, making it more versatile for working with different database systems. PDO also simplifies the code and improves readability compared to using mysql_real_escape_string.

// Using PDO for database interactions
$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 and execute the statement
$stmt->bindParam(':username', $username);
$stmt->execute();

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