4

I want to add a prefix to tables and have recently written a PHP script to extract all tables in a string SQL query.

$sql = 'UPDATE festivals SET desc = "Starts from July"';
preg_match_all('/(from|into|update|table|join) (`?\w+`?)\s/i', $sql, $matches);

It works good but the only problem is that it extracts July because it does not distinguish between a SQL value and a real table name, so it assumes that July would be a table too.

Now I think the solution should be something to prevent extract what wrapped in a single or double quotation but don't know how to do that.

Omid
  • 4,575
  • 9
  • 43
  • 74

2 Answers2

0

If you were more strict in your query-writing, you would wrap all your database, table and column names in backticks ` and they would be extremely easy to extract - just get the first match of a string between them: just make the backticks required instead of optional.

That said, I'm not entirely sure how your regex is matching from July since the July is not followed by whitespace...

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    true, didn't pick that up. maybe he didn't actually test it and is just presenting a hypothetical scenario. – Asad Saeeduddin Oct 14 '12 at 13:42
  • @Kolink Using backticks would be a good idea but just when you are the only developer and not applicable for teamwork. And about `July` this is just an example – Omid Oct 14 '12 at 13:47
  • If you (or your team) can't follow proper standards, then you can't process the task with a regular expression. You would have more luck parsing the query yourself and extracting the tables. Alternatively, you might be able to put `explain` at the start of the query, run it, and then look for the tables listed in the query summary. – Niet the Dark Absol Oct 14 '12 at 14:12
0

Your regex is better off this way:

"/((?:^select .+?(?:from|into))|^update|^table|join) (`?\w+`?)\s/I"

But I still agree with nvartolomei.

Omid
  • 4,575
  • 9
  • 43
  • 74
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139