gpt4 book ai didi

node.js - 如何转义字符串但不影响nodejs mysql js中的LIKE结果

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:56 24 4
gpt4 key购买 nike

最近我在nodejs web应用程序中使用mysqljs。
我想转义 SQL 中的所有参数以防止注入(inject)攻击。
然而,在 LIKE 模式中,SQL 会受到转义字符串符号 `

的影响
Here is my query
SELECT event.name, host.name, Guest.name
FROM Event as event
LEFT JOIN Host on Host._id = event.host_id
LEFT JOIN Event_Guest on Event_Guest.event_id = Event._id
LEFT JOIN Guest on Event_Guest.guest_id = Guest._id
WHERE host._id = event.host_id AND event.status IN ('on', 'off') AND
( event.name LIKE "%?%" escape "'" OR host.name LIKE "%?%" OR guest.name LIKE "%?%")
LIMIT ?, ?;
`, [cond, cond, cond, skip, limit])

如果我应用mysql.escape(cond),SQL将是LIKE "%'cond'%"
单引号会影响结果。

如何转义参数并保留原始 SQL ?

最佳答案

您可以将 % 添加到字符串的开头和结尾,而不是在 SQL 中,您可能也想转义原始字符串。另外,如果你看一下https://github.com/mysqljs/mysql#escaping-query-values您可能会注意到您不需要将值用双引号 (") 括起来。

假设我们正在尝试实现这样的 SQL 查询:

SELECT event.name, host.name, Guest.name
FROM Event as event
LEFT JOIN Host on Host._id = event.host_id
LEFT JOIN Event_Guest on Event_Guest.event_id = event._id
LEFT JOIN Guest on Event_Guest.guest_id = Guest._id
WHERE host._id = event.host_id
AND event.status IN ('on', 'off')
AND (event.name LIKE '%search%' escape "'" OR host.name LIKE '%search%', OR guest.name LIKE '%search')
LIMIT 10, 0;

此更新代码示例可能适合您:

new_cond = cond.slice(0, 1)+'%'+s.slice(1, cond.length-1)+'%'+cond.slice(cond.length-1);
cond = mysql.escape(new_cond); # Should look like '%term%'
status_in = ['on', 'off'];
escape_char = "'";
connection.query('SELECT event.name, host.name, Guest.name
FROM Event as event
LEFT JOIN Host on Host._id = event.host_id
LEFT JOIN Event_Guest on Event_Guest.event_id = Event._id
LEFT JOIN Guest on Event_Guest.guest_id = Guest._id
WHERE host._id = event.host_id
AND event.status IN (?)
AND ( event.name LIKE ? escape ?
OR host.name LIKE ?
OR guest.name LIKE ?
) LIMIT ?, ?;', [status_in, cond, escape_char, cond, cond, skip, limit])

关于node.js - 如何转义字符串但不影响nodejs mysql js中的LIKE结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45317783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com