Sphinx PHP API EscapeString() 函数不适用于 SphinxQL?

Sphinx PHP API EscapeString() function doesn't work for SphinxQL?

我在 Sphinx PHP API 代码中找到了以下函数:

function sphinxapi_EscapeString($string)
{
    $from = ['\', '(', ')', '|', '-', '!', '@', '~', '"', '&', '/', '^', '$', '=', '<'];
    $to   = ['\\', '\(', '\)', '\|', '\-', '\!', '\@', '\~', '\"', '\&', '\/', '\^', '$', '\=', '\<'];

    return str_replace($from, $to, $string);
}

但是,它似乎无法正常工作,因为当我在查询中使用包含某些字符的字符串时,Sphinx 会抛出异常。

引号字符 " 就是一个例子。 EscapeString() 在它前面放一个反斜杠 \,但是 Sphinx 抛出异常说:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 index my_index: syntax error, unexpected $end near ''' in ..

如果我再添加两个反斜杠,使其成为 \\",则不会引发任何错误。

这是怎么回事?为什么 EscapeString() 不工作?

你没有分享你的确切代码,但我想知道你是否只是调用这个函数,也需要按照 SQL 规则转义。

EscapeString 仅转义查询以转义扩展语法字符。

这就是 API 中所需的全部内容,因为 Query/AddQuery 函数直接接受查询。

但在 SphinxQL 中,查询字符串位于 SQL 语句中,因此字符串需要 'SQL String' 在嵌入语句 之前进行转义(无论是还是不是你也像 EscapeString 那样转义)。如果你使用准备好的语句,PDO 可以自动完成,否则使用 PDO quote 函数。

(像 SELECT ... MATCH('one \" ') 这样的查询没有被很好地转义,因为 SQL 解析器的斜杠是 'swallowed',没有进入全文查询解析器)