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

后端 未结 15 2120
我在风中等你
我在风中等你 2021-02-04 01:14

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

15条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 01:46

    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?"

提交回复
热议问题