简体   繁体   English

从SQL查询中提取所有表

[英]Extract all tables from an SQL query

I want to add a prefix to tables and have recently written a PHP script to extract all tables in a string SQL query. 我想为表添加前缀,并且最近编写了一个PHP脚本来提取字符串SQL查询中的所有表。

$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. 它运行良好,但唯一的问题是它提取July因为它不区分SQL值和实际表名,因此它假定July也是一个表。

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. 现在我认为解决方案应该是防止提取包含在单引号或双引号但不知道如何做的内容。

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... 也就是说,我不完全确定你的正则表达式是如何from July开始匹配的from July因为July并没有空白......

Your regex is better off this way: 你的正则表达式更好用这种方式:

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

But I still agree with nvartolomei. 但我仍然同意nvartolomei。

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

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