What are some best practices for using mysqli_real_escape_string function in PHP to prevent SQL injection vulnerabilities?

SQL injection vulnerabilities occur when user input is not properly sanitized before being used in SQL queries, allowing malicious users to manipulate the query and potentially access or modify sensitive data. One way to prevent SQL injection is by using the mysqli_real_escape_string function in PHP to escape special characters in user input before including it in a query. Example PHP code snippet:

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

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

// Get user input from a form
$user_input = $_POST['user_input'];

// Escape the user input using mysqli_real_escape_string
$escaped_input = $mysqli->real_escape_string($user_input);

// Use the escaped input in a SQL query
$query = "SELECT * FROM users WHERE username = '$escaped_input'";
$result = $mysqli->query($query);

// Process the query result
if ($result->num_rows > 0) {
    // Output the data
} else {
    // Handle no results
}

// Close the database connection
$mysqli->close();