2

Several questions were asked on this topic. But I couldn't find the exact answer anywhere. Will the code below cause sql injection? If yes how to escape it?

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)
})

I've tried the code below with mysql.escape(). But SQL query is not working in this case:

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)
})
5
  • Try replacement, most library has it. safest way would be parameterized query, but of course slower. Commented Jul 31, 2020 at 10:05
  • How do you expect it to work like? Commented Jul 31, 2020 at 10:06
  • @AnonyMouze, Parameterized queries are slower? You have measured this? Commented Jul 31, 2020 at 14:45
  • @BillKarwin am not sure about the database execution, but there is extra steps in doing parameterized query most of languages i uses. So it is logically slower. Commented Jul 31, 2020 at 15:07
  • In practice, the difference is much smaller than the query execution time. It's not a good reason to avoid using parameterized queries. Commented Jul 31, 2020 at 17:22

1 Answer 1

3

You can specify the LIKE pattern in the parameter that you pass to the query like so, the parameter will be safely escaped as documented 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);
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.