简体   繁体   English

根据MySQL字段验证PHP数据类型?

[英]Validate PHP data types against MySQL fields?

Long time since I've been on but I've hit kind of a head scratcher of a question and I was wondering if anyone could suggest a solution. 自从上线很长时间以来,我就碰到了一个问题,我想知道是否有人可以提出解决方案。

The Scenario: 场景:

I have number of HTML forms feeding back data via AJAX to a set of PHP PDO query functions. 我有许多HTML表单,它们通过AJAX将数据反馈给一组PHP PDO查询函数。 Although the input will be validated on the form before it is sent I don't want to rely solely on this. 尽管输入将在发送之前在表单上进行验证,但我并不想完全依赖于此。

What I'm asking: 我要问的是:

What I'm after is some means of checking that the type of the PHP parameter passed is compatible with the field type its passing data to. 我需要的是一些方法来检查传递的PHP参数的类型是否与其传递数据的字段类型兼容。 At the moment I'm having to use a huge set of if else statements to check each value in turn and throw Exceptions if there not, so I was wondering if anyone knows of an easier way to check whether a given PHP type is compatible with a given MySQL field type. 目前,我不得不使用大量的if else语句依次检查每个值,如果不存在则抛出Exception,所以我想知道是否有人知道一种更简单的方法来检查给定的PHP类型是否与给定的MySQL字段类型。 I'm sure this must be a problem that's been faced before and if someone could suggest a solution it would save me a great deal of coding and be much appreciated. 我敢肯定,这肯定是一个以前遇到的问题,如果有人可以提出解决方案,那么它将为我节省很多代码,并且深表感谢。

Thanks in advance 提前致谢

You're putting it wrong. 你说错了。
It is not table structure that dictates the data format, but your application logic. 决定数据格式的不是表结构,而是您的应用程序逻辑。 Say, there is a string that should contain only az letters. 假设有一个字符串,只能包含az字母。 You cannot tell it from the field type. 您不能从字段类型中分辨出来。
Yes, there are some formats that can be easily validated, like data or integers, but they are mere exceptions and can't be of much help. 是的,有些格式很容易验证,例如数据或整数,但它们只是例外,没有太大帮助。

Most of time form validation is indeed a long code with custom validations and you cannot avoid it. 大多数情况下,表单验证确实是带有自定义验证的长代码,您无法避免。 However, I wouldn't throw exceptions in case of failed validation as it is considered more user friendly to show all the errors occurred, not just one. 但是,在验证失败的情况下,我不会抛出异常,因为它被认为更易于使用,可以显示所有发生的错误,而不仅仅是一个错误。

If you still want some automated checking - look for some ORM, which will indeed do some validations... for the price of writing much more code in the model, than you writing right now with your validations :) 如果您仍然希望进行一些自动检查,请寻找一些ORM,它确实会进行一些验证……与在模型中编写更多代码相比,现在进行验证需要付出更多的代价:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM