返回MySQL实体 [英] Backticking MySQL Entities
问题描述
我有以下方法可以保护MySQL实体:
public function Tick($ string)
{
$ string = explode('。',str_replace('`','',$ string));
foreach($ string as $ key => $ value)
{
if($ value!='*')
{
$ string [$ key] ='`'。修剪($ value)。 `;
}
}
返回implode('。',$ string);
}
这对我的使用来说相当不错。 >
它保护数据库,表,字段名称甚至*运算符,但是现在我也希望它保护函数调用,即:
AVG(database.employees.salary)
应该成为:
AVG(`database`.`employees`.`salary`)而不是`AVG(database`.`雇员```salary)`
我该怎么办?我应该使用正则表达式吗?
此外,我如何支持更高级的内容:
MAX(AVG(database.table.field1),MAX(database.table.field2))
至:
MAX(AVG `database`.`table`.`field1`),MAX(`database`.`table`.`field2`))
请记住,我想保持这种方法尽可能简单/快速,因为它几乎遍历数据库中的所有实体名称。
使用测试用例 ndp 给了我创建一个正则表达式为你做的辛勤工作。以下正则表达式将替换开头圆括号后面的所有单词边界。
\b(\w + )\b(?!\()
Tick()功能将被实现在PHP如下:
function Tick($ string)
{
return preg_replace('/ \ b(\w +)\b(?!\()/','`\1`',$ string);
}
I've the following method which allows me to protect MySQL entities:
public function Tick($string)
{
$string = explode('.', str_replace('`', '', $string));
foreach ($string as $key => $value)
{
if ($value != '*')
{
$string[$key] = '`' . trim($value) . '`';
}
}
return implode('.', $string);
}
This works fairly well for the use that I make of it.
It protects database, table, field names and even the * operator, however now I also want it to protect function calls, ie:
AVG(database.employees.salary)
Should become:
AVG(`database`.`employees`.`salary`) and not `AVG(database`.`employees`.`salary)`
How should I go about this? Should I use regular expressions?
Also, how can I support more advanced stuff, from:
MAX(AVG(database.table.field1), MAX(database.table.field2))
To:
MAX(AVG(`database`.`table`.`field1`), MAX(`database`.`table`.`field2`))
Please keep in mind that I want to keep this method as simple/fast as possible, since it pretty much iterates over all the entity names in my database.
Using the test case ndp gave I created a regex to do the hard work for you. The following regex will replace all word boundaries around words that are not followed by an opening parenthesis.
\b(\w+)\b(?!\()
The Tick() functionality would then be implemented in PHP as follows:
function Tick($string)
{
return preg_replace( '/\b(\w+)\b(?!\()/', '`\1`', $string );
}
这篇关于返回MySQL实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!