What are the potential issues when using htmlspecialchars and mysqli_real_escape_string together in PHP?

When using htmlspecialchars and mysqli_real_escape_string together in PHP, the order in which these functions are applied is important. It is recommended to first use mysqli_real_escape_string to escape special characters in SQL queries to prevent SQL injection attacks, and then apply htmlspecialchars to encode special characters in HTML output to prevent XSS attacks.

// Example of using mysqli_real_escape_string followed by htmlspecialchars
$input = $_POST['input'];
$escaped_input = mysqli_real_escape_string($connection, $input);
$encoded_input = htmlspecialchars($escaped_input);

// Now $encoded_input can be safely used in SQL queries and HTML output