I have a class that is used to insert data into the database, and the information passed to this class’ methods must be escaped and validated. What is the best practice for validating and escaping data? Should it be done inside the method’s implementation, or should it be done in the script file that is using the class, so that the information is valid and secured before moving onto the class? I have done it both ways in the past and have always wondered which way it was that most people did it. (I code in PHP if it matters, but it seems more like a general programming practices question to me.)
Thank you!
This somewhat depends on the type of architecture you have with regards to your data processing, but…
In general, classes which insert data into the database (Let’s call them persistence classes) should perform SQL escaping. If the values must be of specific types (eg. VARCHAR, INT), it could also validate those, or leave it up to the database to throw up an error for incorrect data types.
For more specific validation, it would probably be a good idea to include it in your domain models or other code which processes the immediate inputs (eg. GET and POST).
If you use domain model objects, they should contain a method that can be used to make sure they are valid, or alternatively they should not accept data that is not valid as per the requirements of the model. The persistence class could then simply deal with the domain objects, or through the domain object’s repository.
In a simpler scenario where you only have a script with less separate layers, the validation of data should probably be done before the script hands the data over to the persistence class. (In PoEAA this is probably closest to the transaction script pattern, if you’re curious)