Obto
Obto

Reputation: 1417

Validate data before insert/update or no?

If you have properly defined checks and assertions in your DB (e.g., MySQL), is it good practice or even worth validating data before you update or insert a record into a DB like MySQL?

From what I see, as long as the checks you have to perform are not complicated and can be accomplished by the DB itself, it looks wasteful to validate the data in say... PHP first and THEN MySQL again.

Am I correct on this?

Upvotes: 3

Views: 1399

Answers (2)

Jonathan Hall
Jonathan Hall

Reputation: 79576

As a general rule, you should do validation as soon as possible. This means in your PHP code in this case. Why?

  1. It's more efficient. Why send data to the database (which might be over a network, or even in a different country) if it's only going to respond with an error? Better to avoid the error first.

  2. It makes it much easier to report a useful/friendly error message to your user. Sometimes it might be possible to parse a DB error sufficiently to generate a useful error message, but most DB errors don't look very friendly to end-users. It's better to generate the error as close to the user as possible.

Now, even with this, it's still good to have checks in your DB, but they should act as a last resort, and when your DB throws an error, it should be considered a bug, not a "data validation feature." In other words, if you ever get a DB exception, it's an indication that your PHP code is broken.

Exception: There was one time recently when I chose to violate this principle, because of some rather complex validation that was necessary. I opted to rely on the DB for the "complete" validation (but made sure my exception text was easily parsed, so a user-friendly error could still be generated). I still had my client-side code do basic input validation, but because of the complexity involved in the complete validation, I did not want to have to maintain two functionally-identical bits of code (one in the client software, one in the DB). I felt that having the same functionality in two places was more likely to lead to future bugs, in case one got updated and the other didn't. In this case, the server-side validation code was about a 4-page long PL/Perl stored procedure that acted as an INPUT/UPDATE trigger.

Conclusion: Almost never should you rely on the DB for your user validation. The only exceptions I can think of are the opposite of what you're asking about: Really complex checks; not the really simple ones.

Upvotes: 5

JM4
JM4

Reputation: 6788

100% Incorrect.

Is it good practice or even worth validations before you update or insert a record into a DB like MySQL?

It not only is 'good' practice, it is basic logic. You wouldn't use MySQL to do the checks at all. PHP would do the validation based on rules you set. If those rules don't mean certain criteria, throw an error up.

Upvotes: 1

Related Questions