避免在 Node js 的 SQL LIKE 查询中注入
Avoid injection in SQL LIKE query in Node js
就此主题提出了几个问题。但我无法在任何地方找到确切的答案。
下面的代码会导致 sql 注入吗?如果是怎么转义?
db.query('SELECT USER.id, USER.username FROM USER LEFT JOIN user_photo photo ON USER.id = photo.user_id WHERE USER.username LIKE "%' + search + '%"', (err, result) => {
if (err) throw err
res.send(result)
})
我已经用 mysql.escape()
尝试了下面的代码。但是 SQL 查询在这种情况下不起作用:
db.query('SELECT USER.id, USER.username FROM USER LEFT JOIN user_photo photo ON USER.id = photo.user_id WHERE USER.username LIKE "%' + mysql.escape(search) + '%"', (err, result) => {
if (err) throw err
res.send(result)
})
您可以像这样在传递给查询的参数中指定 LIKE 模式,该参数将按照记录进行安全转义 here
let search = "Terry";
let sql = `SELECT USER.id, USER.username FROM USER
LEFT JOIN user_photo photo
ON USER.id = photo.user_id WHERE USER.username LIKE ?`;
db.query(sql, [`%${search}%`], (err, result) => {
if (err) throw err
res.send(result);
})
就此主题提出了几个问题。但我无法在任何地方找到确切的答案。 下面的代码会导致 sql 注入吗?如果是怎么转义?
db.query('SELECT USER.id, USER.username FROM USER LEFT JOIN user_photo photo ON USER.id = photo.user_id WHERE USER.username LIKE "%' + search + '%"', (err, result) => {
if (err) throw err
res.send(result)
})
我已经用 mysql.escape()
尝试了下面的代码。但是 SQL 查询在这种情况下不起作用:
db.query('SELECT USER.id, USER.username FROM USER LEFT JOIN user_photo photo ON USER.id = photo.user_id WHERE USER.username LIKE "%' + mysql.escape(search) + '%"', (err, result) => {
if (err) throw err
res.send(result)
})
您可以像这样在传递给查询的参数中指定 LIKE 模式,该参数将按照记录进行安全转义 here
let search = "Terry";
let sql = `SELECT USER.id, USER.username FROM USER
LEFT JOIN user_photo photo
ON USER.id = photo.user_id WHERE USER.username LIKE ?`;
db.query(sql, [`%${search}%`], (err, result) => {
if (err) throw err
res.send(result);
})