如果我总是用PHP控制我的数据库输入,约束像NOT NULL和FOREIGN KEY有多重要? [英] How important are constraints like NOT NULL and FOREIGN KEY if I'll always control my database input with PHP?
问题描述
我试图在一个外键的表中创建一个列,但在MySQL中比它应该更困难。这将需要我回去并对已经在使用的表进行某些更改。所以我不知道, MySQL是否有必要确保某个值是否合适?
与NOT NULL类似。如果我只用PHP访问这个数据库,我不能简单地让PHP确保没有输入空值。
为什么我应该使用MySQL来执行这些约束,当我只能用PHP做它?
我意识到NOT NULL是一个非常愚蠢的部分由于上述原因而忽视。但是MySQL没有强制外键,没有严重的猴子。
在你看来,使用假外键还是不好,
只要检查要输入的值是否在其他表中与PHP匹配即可
em>与PHP进行错误,100%保证。 PHP是程序性的。你想要的是声明约束。你想告诉整个栈:这些是对数据的约束,并且不能违反这些约束。你不想对步骤1 ...步骤2 ...步骤3 ...步骤432 ...作为实施数据约束的方法,因为问题应该是写的, 为什么我应该使用PHP来强制执行这些约束,当我只用MySQL做?
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?
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?"
这篇关于如果我总是用PHP控制我的数据库输入,约束像NOT NULL和FOREIGN KEY有多重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!