How can the use of mysqli_real_escape_string() improve the security of a PHP script that interacts with a MySQL database?
Using mysqli_real_escape_string() helps prevent SQL injection attacks by escaping special characters in user input before sending them to the database. This function ensures that any potentially harmful characters are properly handled, making it more difficult for attackers to manipulate the SQL queries.
// Establish a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Get user input
$user_input = $_POST['user_input'];
// Escape user input
$escaped_input = mysqli_real_escape_string($connection, $user_input);
// Query the database using the escaped input
$query = "SELECT * FROM users WHERE username='$escaped_input'";
$result = mysqli_query($connection, $query);
// Process the query result
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "Username: " . $row["username"];
}
} else {
echo "No results found.";
}
// Close the connection
mysqli_close($connection);
Related Questions
- What could be causing a PHP script to only function when directly accessed, but not when called from another HTML page?
- In what ways can different web browsers impact the display and functionality of PHP scripts, as seen in the case of Internet Explorer and Netscape Navigator in the forum discussion?
- In what situations is it recommended to switch to object-oriented programming in PHP, especially when dealing with database connections and queries?