How can prepared statements or mysql_real_escape_string() be used to prevent SQL injection attacks in PHP MySQL queries?

SQL injection attacks can be prevented in PHP MySQL queries by using prepared statements or the mysql_real_escape_string() function. Prepared statements allow for the separation of SQL logic from user input, preventing malicious input from being executed as SQL commands. mysql_real_escape_string() escapes special characters in a string to prevent SQL injection.

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

// Using mysql_real_escape_string() to prevent SQL injection
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query);