How does using prepared statements in PHP with PDO or MySQLi provide better protection against SQL injection compared to mysql_real_escape_string()?

Using prepared statements in PHP with PDO or MySQLi provides better protection against SQL injection compared to mysql_real_escape_string() because prepared statements separate SQL code from user input. This means that the SQL query and the user input are sent to the database server separately, preventing malicious SQL code from being executed. Prepared statements also automatically handle escaping of special characters, reducing the risk of SQL injection attacks.

// Using prepared statements with PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();