htmlspecialchars() vs mysql_real_escape_string..??? confused

Solution One

It depends on what your application is. If it doesn’t involve databases, then there’s no need to call mysql_real_escape_string(), similarly if the input needs to be in HTML then htmlspecialchars() would not be appropriate. However, if you are inserting untrusted content into a database that will in the future be output to a HTML page and you do not want said output’s HTML code to be parsed, then you should modify the input with both. Note that it is more common (and generally better) to invoke htmlspecialchars() when output occurs.

Solution Two

They are used for completely different things. htmlspecialchars() converts special HTML characters into entities so that they can be output without problems (or a risk of XSS), while mysql_real_escape_string() escapes sensitive SQL characters so interpolated queries can be performed without the risk of SQL injection.

Simply said:

real_escape_string is for making a legal query to INPUT
htmlspecialchars is used for legal OUTPUT to your html/xhtml


Stack Overflow