dongsong73032 2011-12-13 01:21
浏览 87
已采纳

在插入/更新之前验证数据还是否?

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?

  • 写回答

2条回答 默认 最新

  • dtt27783 2011-12-13 02:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了