Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How important are constraints like NOT NULL and FOREIGN KEY if I'll always control my database input with PHP?

Tags:

I am trying to create a column in a table that's a foreign key, but in MySQL that's more difficult than it should be. It would require me to go back and make certain changes to an already-in-use table. So I wonder, how necessary is it for MySQL to be sure that a certain value is appropriate? Couldn't I just do that with a language like PHP, which I'm using to access this database anyway?

Similarly with NOT NULL. If I only access this database with PHP, couldn't I simply have PHP ensure that no null value is entered?

Why should I use MySQL to do enforce these constraints, when I could just do it with PHP?


I realize that NOT NULL is a very stupid part to neglect for the above reasons. But MySQL doesn't enforce foreign keys without a serious degree of monkeying around.

In your opinion, would it still be bad to use the "fake" foreign keys, and simply check if the values to be entered are matched in other tables, with PHP?

like image 899
stalepretzel Avatar asked Dec 19 '08 21:12

stalepretzel


1 Answers

You are going to make mistakes with PHP, 100% guaranteed. PHP is procedural. What you want are declarative constraints. You want to tell the entire stack: "These are the constraints on the data, and these constraints cannot be violated." You don't want to much around with "Step 1 ... Step 2 ... Step 3 ... Step 432 ...", as your method of enforcing constraints on data, because

  • you're going to get it wrong
  • when you change it later, you will forget what you did now
  • nobody else will know all of these implicit constraints like you know them now, and that includes your future self
  • it takes a lot of code to enforce constraints properly and all the time - the database server has this code already, but are you prepared to write it?

The question should actually be worded, "Why should I use PHP to enforce these constraints, when I could just do it with MySQL?"

like image 104
yfeldblum Avatar answered Oct 08 '22 17:10

yfeldblum