最近我在nodejs web app中使用mysqljs 我想在SQL中转义所有参数以防止注入攻击 但是在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'%"
单引号会影响结果。
如何转义params并保留原始SQL?
答案 0 :(得分:1)
您可以将%
添加到字符串的开头和结尾而不是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])