What are the differences between mysql_real_escape_string and htmlspecialchars in PHP?

When dealing with user input in PHP, it is important to sanitize the data to prevent SQL injection attacks and cross-site scripting vulnerabilities. mysql_real_escape_string is used to escape special characters in a string that is to be used in an SQL query, while htmlspecialchars is used to convert special characters to HTML entities to prevent XSS attacks. To properly sanitize user input, it is recommended to use mysql_real_escape_string for database queries and htmlspecialchars for displaying user input on a webpage.

// Using mysql_real_escape_string for database queries
$user_input = mysql_real_escape_string($_POST['user_input']);
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysql_query($query);

// Using htmlspecialchars for displaying user input on a webpage
echo "Welcome back, " . htmlspecialchars($_SESSION['username']) . "!";