I got hacked using PDO

I don’t agree with your take on security:

There’s nothing wrong about relying on htmlentities (or htmlspecialchars) to prevent XSS because it’s effective. In fact, I think it is good practice to output any textual data from the db through htmlentities - do you suggest that we should use htmlentities only on data that has been properly validated? This is crazy, htmlentities is used in the code that is responsible for outputting data to the browser (like templates or views) and thinking whether each db field has the code somewhere else to validate data or not is unnecessary burden and doesn’t belong there. And what if one day you change how a field is validated? You’d have to go through all its usages in the templates and add or remove htmlentities - this results in nothing but a mess. All textual data should go through htmlentities or htmlspecialchars regardless of how much validation they have gone through. Besides, sometimes data can enter the database via other ways than your validating script so you can never be sure if it is safe to avoid escaping.

It looks like you are mixing validation with security and it can lead to unnecessary mess. I think validation should be kept separate from security (escaping). If you rely on proper validation to guarantee security then it becomes easier to find a dangerous loophole. Validation is about making sure that only data that make sense go into the db. But regardless of what data gets into the db, if this data is text entered by a user, the application should be made so that it remains secure no matter what garbage it is fed. And in most cases htmlentities is all that is required for displaying in HTML.

Also, I think it is good not to over-validate data if not absolutely necessary. For example, I see many people strip_tags() from every piece of text that comes from a form into the db. This way if someone enters some malicious html/javascript code it gets cleaned but at the same time I, as the owner of the site, don’t really know what was entered. The data may be rejected altogether by the validation scripts but this doesn’t mean I shouldn’t secure my application in the templates. If there is an attacker I prefer to know what he was trying to do and I want to see all the code he wanted to inject into my website, because that may help me identify the threat and learn more about it. It’s really not that hard to remember to escape all text data to the browser and then all such malicious scripts pose no threat since they are simply displayed as text for everyone to see.