What are the potential risks of using mysqli_real_escape_string() for preventing SQL-Injection?
Using mysqli_real_escape_string() can help prevent SQL-Injection by escaping special characters in a string before sending it to the database. However, it is not foolproof and can still be vulnerable to certain types of attacks if not used correctly. It is important to also use prepared statements or parameterized queries in conjunction with mysqli_real_escape_string() to fully protect against SQL-Injection.
// Example of using mysqli_real_escape_string() with prepared statements to prevent SQL-Injection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Using prepared statements with placeholders
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);
// Escape user input for security
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// Execute the statement
$stmt->execute();
// Close the connection
$stmt->close();
$conn->close();