Lua SQL转义字符串(尝试)未完成的字符串位于“' }”附近。

function escape_sqli(source)
    to_replace = {"'", '"'}
    replace_with = {"\'", '\"'} # 将单引号和双引号替换为转义的形式
    output = source
    for i = 1, table.getn(to_replace) do
        output = string.gsub(output, to_replace[i], replace_with[i])
    end
    return output # 返回转义后的字符串
end

我尝试运行上面的代码来转义 SQL 语句,但当我尝试编译它时,出现以下错误:

未完成字符串,靠近““}”
点赞
用户1190388
用户1190388

目前这个代码中没有语法错误。


不过,有一个建议,根据string.gsub的官方文档:

string.gsub (s, pattern, repl [, n])

[...]

如果repl是一个表,则该表会在每次匹配时被查询,将第一个捕获作为键。

您可以简单地按照以下方式重新创建替换表:

local replacements = { ['"'] = '\\"', ["'"] = "\\'" }

并在一个gsub调用中使用它:

function escape_sqli(source)
    local replacements = { ['"'] = '\\"', ["'"] = "\\'" }
    return source:gsub( "['\"]", replacements ) -- or string.gsub( source, "['\"]", replacements )
end
2015-03-01 18:39:13