就这个主题提出了几个问题。但我在任何地方都找不到确切的答案。下面的代码会导致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模式,这样,参数将安全地转义,如所示
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);
})