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);