Generally speaking your flow will be similar to this:
"Validate" data client side - you don't want to trust this validation since you should never trust anything coming from the client, this is done to make the user experience better.
Validation on the server - make sure the data given to you is valid. Examples might be: validate type (int, string, etc.), validate value (users can't order a negative amount of an item), etc. If you're using some kind of MVC-ish framework this is done in the Model layer.
Store the data in the database - you'll use prepared statements to protect yourself from SQL injection but you don't want to manipulate the data in any way (no
htmlentities
or the like).Whenever you're taking data out of the database that's when you decide if you need to convert HTML entities or do some other processing based on whether you're outputting HTML, JSON, XML, etc.
If you need to use htmlspecialchars
or something like that on data in a JSON array, execute that before you put the data in the JSON array.