How can mysqli_real_escape_string help prevent SQL injection in PHP scripts?
SQL injection occurs when malicious SQL queries are inserted into input fields of a web form, allowing attackers to manipulate the database. mysqli_real_escape_string helps prevent SQL injection by escaping special characters in a string before sending it to the database, making it safe to use in SQL queries.
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection is successful
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Escape user input to prevent SQL injection
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
// Query the database using the escaped user input
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Process the query result
if (mysqli_num_rows($result) > 0) {
// User authentication successful
} else {
// User authentication failed
}
// Close the database connection
mysqli_close($connection);