Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a PHP application perform error handling on incorrect database values?

Tags:

database

php

Imagine this... I have a field in the database titled 'current_round'. This may only be in the range of 0,1,2,3.

Through the application logic, it is impossible to get a number above 3 or less than 0 into the database.

Should there be error checking in place to see if the value is malformed (i.e. not in the range 0-3)? Or is this just unnecessary overhead? Is it OK to assume values in a database are correctly formatted/ranged etc (assuming you sanatise/evaluate correctly all user input?)

like image 993
alex Avatar asked Apr 24 '26 09:04

alex


2 Answers

I generally don't validate all data from the database. Instead I try to enforce constraints on the database. In your case depending on the meaning of 0, 1, 2, 3 I might use a lookup table with a foreign key constraint or if they are just numeric values I might use a check constraint (differs from DB vendor to the next).

This helps protect against changes made to the DB by someone with direct access and/or future applications that may use the same DB but not share your input validation process.

like image 141
Brian Fisher Avatar answered Apr 26 '26 22:04

Brian Fisher


Wherever you decide to place validation prior to insertion in the database is where you should catch these things.

The process of validation should take place in one place and one place only. Depending on how your application is structured:

  • Is it procedural or object oriented?
  • If it is object oriented, then are you using an Active Record pattern, Gateway pattern or Data Mapper pattern to handle your database mapping?
  • Do you have domain objects that are separate from your database abstraction layer?

Then you will need to decide on where to place this logic in your application.

In my case, domain objects contain the validation logic and functions with data mappers that actually perform the insert and update functions to the database. So before I ever attempt to save information to the database, I confirm that there are valid values.

like image 29
Noah Goodrich Avatar answered Apr 26 '26 23:04

Noah Goodrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!