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);
Related Questions
- What best practices should be followed in PHP to ensure proper handling of special characters in input data from different sources like mobile devices?
- How can the PHP_SELF variable be used securely in PHP forms?
- What potential pitfalls should be considered when creating dynamic form fields in PHP, especially when it comes to handling user input?