封闭'
的 s 由转义函数自动添加,因此将%
s 移动到变量内部并将其转义,然后'
从查询中删除 s:
input = client.escape('%' + input + '%'); //=== "'%escaped_input%'"
client.query("SELECT * FROM posts WHERE (title LIKE " + input + ") or (content LIKE " + input + ")", function(err, results) {
// ...
});
或者,您也应该能够使用模拟的预处理语句语法:
input = '%' + input + '%';
client.query("SELECT * FROM posts WHERE (title LIKE ?) or (content LIKE ?)", [input, input], function(err, results) {
// ...
});
This will perform something similar to sprintf
, replacing the ?
placeholders by the properly escaped items (internally using the same escape
method as above) from second argument array, in the order they were passed - the placeholders' order corresponds to the array items' order.
Side-note: I assume you've oversimplified the query removing all the fields from SELECT
statement, remember to select at least a field or all of them (*
) otherwise it is not valid SQL syntax.