How effective is the use of mysqli_real_escape_string in PHP to protect against SQL injection, when used in conjunction with limiting character lengths?
Using mysqli_real_escape_string in PHP can help protect against SQL injection by escaping special characters in user input. However, it is not foolproof and should be used in conjunction with other security measures, such as limiting character lengths of input fields. By combining these two techniques, you can reduce the risk of SQL injection attacks.
// Example of using mysqli_real_escape_string and limiting character lengths to protect against SQL injection
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Escape user input and limit character length
$username = mysqli_real_escape_string($conn, substr($_POST['username'], 0, 50));
$password = mysqli_real_escape_string($conn, substr($_POST['password'], 0, 50));
// Perform SQL query using the escaped and limited user input
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
// Process the query result
if ($result->num_rows > 0) {
// User authenticated
} else {
// User not found
}
// Close the database connection
$conn->close();