Hi I was wondering when is the appropriate place to use htmlspecialchars(). Is it before inserting data to database or when retrieving them from the database?
You use htmlspecialchars EVERY time you output content within HTML, so it is interperted as content and not HTML.
htmlspecialchars
If you allow content to be treated as HTML, you have just opened the door to bugs at a minimum, and total XSS hacks at worst.