Jos*_*son 1 php mysql database arrays escaping
所以我创建了一个简单的PHP函数,只需通过更新PHP接收的数组来"更新"我的MySQL行.
function db_updateproduct(array $new, array $old = array()) {
$diff = array_diff($new, $old);
return 'INSERT INTO table (`'.mysql_real_escape_string(implode(array_keys($diff), '`,`')).'`) VALUES \''.mysql_real_escape_string(implode(array_values($diff), '\',\'')).'\'';
}
Run Code Online (Sandbox Code Playgroud)
...
更新(已接受的答案)
function db_updateproduct(array $new, array $old = array()) {
$diff = array_diff($new, $old);
return 'INSERT INTO `Product` (`'.implode(array_keys($diff), '`,`').'`) VALUES (\''
.implode(array_map('mysql_real_escape_string', array_values($diff)), '\', \'').'\')';
}
Run Code Online (Sandbox Code Playgroud)
现在...
echo db_updateproduct(array('a' => 'on\'e', 'b' => 'two', 'c' => 'three'));
Run Code Online (Sandbox Code Playgroud)
收益:
INSERT INTO `Product` (`a`,`b`,`c`) VALUES ('on\'e', 'two', 'three')
Run Code Online (Sandbox Code Playgroud)
(正如预期/想要的那样!)
您可以使用以下命令对键和值运行转义函数array_map():
$ escaped_keys = array_map('mysql_real_escape_string',array_keys($ diff));
$escaped_values = array_map('mysql_real_escape_string', array_values($diff));
Run Code Online (Sandbox Code Playgroud)
然后你可以implode()在这两个数组上做你的魔术.
mysql_real_escape_string()在查询中使用的值作为字段名称/表名/等运行并没有多大意义.它正确地逃脱\x00,\n,\r,\,',"和\x1a,但不会逃避反引号,所以查询仍容易受到攻击.
您应该验证字段名称(因此只能使用预期的名称)或甚至更好,使用准备好的查询(我建议使用PDO).
建议阅读: