when to use htmlspecialchars() function?

Solution 1:

You should only call this method when echoing the data into HTML.

Don't store escaped HTML in your database; it will just make queries more annoying.
The database should store your actual data, not its HTML representation.

Solution 2:

You use htmlspecialchars EVERY time you output content within HTML, so it is interperted as content and not HTML.

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.

Solution 3:

Save the exact thing that the user enters into the database. then when displaying it to public, use htmlspecialchars(), so that it offers some xss protection.