How does using mysqli_real_escape_string differ from addslashes in terms of protecting against SQL injection in PHP?
Using mysqli_real_escape_string is preferred over addslashes for protecting against SQL injection in PHP because it is specifically designed for escaping characters in SQL queries. It takes into account the current character set of the connection, making it more reliable in preventing SQL injection attacks. On the other hand, addslashes may not escape all characters that could be used in an SQL injection attack, leaving potential vulnerabilities in your code.
// Using mysqli_real_escape_string to protect against SQL injection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Escape user input for security
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// User authenticated
} else {
// Invalid credentials
}
$conn->close();
Related Questions
- What is the best practice for storing a variable in connection with text as a separate variable in PHP?
- What common formatting issue occurs when using TinyMCE with PHP echo output?
- What legal considerations should be taken into account when scraping data from external websites for display on one's own site?