How does PDO compare to mysql_escape_string for protecting against SQL injection attacks?
PDO is a more secure method for protecting against SQL injection attacks compared to mysql_escape_string. PDO uses prepared statements and parameterized queries to separate SQL code from user input, making it more difficult for attackers to inject malicious code into queries. On the other hand, mysql_escape_string simply escapes special characters in a string, which can still leave room for vulnerabilities.
// Using PDO to protect against SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with placeholders
$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();