I've searched a lot of the questions here and I found that they either very old or suggesting using prepared statements PDO which I am not using. So I need your help please.
I have a small discussion/chat box where a user submit a message using a
First, keep the text logical and clean:
trim() -- OK htmlentities($comment, ENT_NOQUOTES) -- No; do later mysqli_real_escape_string() -- Yes; required by API nl2br() -- No; see below
The logic behind those recommendations: The data in the database should be just plain data. Not htmlentities, not br-tags. But, you must do the escape_string in order to pass data from PHP to MySQL; the escapes will not be stored.
But... That is only the middle step. Where did the data come from? Older versions of PHP try to "protect" you be adding escapes and other junk that works OK for HTML, but screws up MySQL. Turn off such magic escaping, and get the raw data.
Where does the data go to? Probably HTML? After
SELECTing the data back out of the table, then first do
htmlentities() and (optionally)
Note, if you are expecting to preserve things like
<I> (for italic), you are asking for trouble -- big trouble. All a hacker needs to do is
<script> ... to inject all sorts of nastiness into your web page and possibly your entire system.