I’m adding an if statement to my database abstraction layer to pick out any attempted queries to a handful of database tables.
Basically, if my application attempts to create, read or destroy data from a database table called either members or members_profiles I want to invoke my if statement.
if (
preg_match('/INSERT INTO [members|members_profiles]/', $sql) ||
preg_match('/UPDATE [members|members_profiles]/', $sql) ||
preg_match('/DELETE FROM [members|members_profiles]/', $sql))
{
// do if statement stuff here...
}
I’m no regular expression/preg-match master, but will the above if statement return true if a SQL query matches:
INSERT INTO members ...orINSERT INTO members_profiles ...UPDATE members ...orUPDATE members_profiles ...DELETE FROM members ...orDELETE FROM members_profiles ...
Or is my preg-match syntax way off?
Just one regex will be enough:
note the
()instead of[]and\s+instead of spaces. because SQL is valid with any number of nay whitespace, and\s+matches them all. The+behind\smeans that it must be at least one whitespace, but it can be more. The(?i)means that all following characters will be checked case insensitive, and the(?-i)turn case sensitivity on again. Since SQL commands are case insensitive.(abc|def)matchesabcordef[abc|def]matchesa,b,c,|,d,eorfTo try out a regular expression you can use http://rubular.com/, it says it’s written in ruby for testing regex in ruby, but valid regex should be independent of language, so it can be used to test common regular expressions, that work in other languages, too.