How can the "real_escape_string" command be used to prevent SQL injection in PHP?

To prevent SQL injection in PHP, the "real_escape_string" command can be used to escape special characters in user input before sending it to the database. This function ensures that any potentially harmful characters are properly handled, 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 for a successful connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Escape user input using real_escape_string
$user_input = $mysqli->real_escape_string($_POST['user_input']);

// Prepare and execute the SQL query
$sql = "SELECT * FROM table WHERE column = '$user_input'";
$result = $mysqli->query($sql);

// Process the query result
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Process each row of data
    }
} else {
    echo "No results found";
}

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