How can mysqli_real_escape_string be used to prevent SQL injection in PHP?

SQL injection is a common attack where malicious SQL statements are inserted into an entry field, allowing an attacker to manipulate the database. To prevent SQL injection in PHP, you can use the mysqli_real_escape_string function to escape special characters in a string before sending it to the database. This function ensures that any special characters in the input are properly escaped, preventing them from being interpreted as part of the SQL query.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Escape user input to prevent SQL injection
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);

// Perform a SQL query using the escaped input
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $mysqli->query($query);

// Process the query result as needed