Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

285
Vistas
Avoid injection in SQL LIKE query in Node js

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)
})
9 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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);
})
9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos