Reputation: 483
Just wondering, if is there any class, function or ideia on how to validate a specific value/variable against a mysql data type.
We've got in PHP the is_int() is_string() is_float() etc etc... But we do not have them all. Or do we? Any Cheat sheet? Any thoughts?
EDIT: The point basically is:
Upvotes: 0
Views: 2611
Reputation: 1387
If the data is coming from a CSV file, you have to remember that all the values are going to be strings (even numeric strings still have a string type).
So you can't use is_int()
/is_float()
/etc., because that only tells you about the type or the variable. You could use is_numeric()
to check the value, but this will allow for things like exponential notation like "+0123.45e6". Sometimes ctype_digit()
can be useful for testing integers for this reason, since it will only allow the numbers 0-9 to be present in a string for it to return true.
Regular expressions can also be used to identify pattern-based data types, but you do have to watch for performance overhead when dealing with large data sets. It's almost always advisable from a performance perspective to use the preg_
family of functions instead of the ereg
functions.
If you're validating things like ENUM or SET types, you'll probably need to make an array containing legal values (or extract these with a query) and then check the value against them with in_array()
.
For CHAR/VARCHAR fields, you could parse the column definition and then check whether the length of the value falls within the constraints.
If the NULL type is allowed on any of your columns, you'd also need to check against this (and probably map empty values or the string "NULL" to an actual NULL value).
If you're looking to actually escape these values properly, look into using prepared statements and the PDO (PHP Data Objects) extension. This allows MySQL to properly escape the data based on type. (You can also use prepared statements with MySQLi.)
If you're looking for specific data types and how to identify them, then you might want to edit your question to facilitate more complete answers.
Upvotes: 1