0

I'm new to MySQL, and am wondering: Is it possible to make a table check attempted inserts against some sort of pattern match, and reject any inserts that fail to match the pattern, or must this checking all be done PHP / what-ever-server-side-language side?

I'm thinking specifically about confining an email column in a user table to only be able to contain email addresses using some sort of regex-like pattern matching.

Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80

2 Answers2

1

Because you can do something with a DBMS stored procedure doesn't make it a good idea. I strongly suggest you do this kind of validation in PHP rather than in the DBMS.

PHP's install kit contains a validator for email. See here: http://php.net/manual/en/filter.filters.validate.php

If you do this in your DBMS you have to reinvent the flat tire, er, wheel.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
1

Although an answer was already accepted, I believe there are use cases for doing validation on the db side.

  1. It's an extra layer of security. While there is such a thing as overkill I think the case could be made that no matter how well you validate on the application side and use parameter binding with PDO there is always a possibility someone figures out a way to get around it.

  2. If the same data might be used by more than one application, it enforces rules in case a developer for a different app fails to validate correctly.

Here is a example of validation using triggers in mysql. http://cvuorinen.net/2013/05/validating-data-with-triggers-in-mysql/

And here you can see how you might replace the code in those IF statements with regex. regular expressions inside a SQL IF statement

I haven't tried it so don't know if it works but there is a link to the mysql docs on regex. http://dev.mysql.com/doc/refman/5.1/en/regexp.html

And of course you should always validate on the application side too.

Community
  • 1
  • 1
isimmons
  • 2,016
  • 2
  • 20
  • 32