9

I am currently using the node-mysql library to connect my application to a MySQL instance. After reading some other StackOverflow questions and articles I found, it sounds like node-mysql automatically escapes unsafe characters every time the query() method is called. But on some code snippets, I also see mysql.escape() and mysql.escapeId() being called within the query() method.

It seems like that while query() automatically escapes some dangerous characters, you should still call mysql.escape() and mysql.escapeId() to escape other dangerous characters.

Is this correct? If so, what kind of SQL injection attacks are automatically protected against by the query() method and what kind of SQL injection attacks are protected by calling mysql.escape() and mysql.escapeId()?

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248

2 Answers2

28

No, query() does not automatically escape unsafe characters.

To safely escape values, you need to use mysql.escape()/mysql.escapeId() or use ? placeholders as described here:

https://github.com/felixge/node-mysql#escaping-query-values

connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  // ...
});
go-oleg
  • 19,272
  • 3
  • 43
  • 44
0

And this is how to escape INSERT VALUES() because all examples everywhere is with ? for SET method, for escaping VALUES(Data,Data) that are separate by comma you can use template string. Also escape command when data are empty its replace by NULL

(`INSERT INTO data VALUES (NULL,${c.escape(data.Name)},${c.escape(data.age)},${c.escape(data.emptystring)})`,
//INSERT INTO data VALUES (NULL,'Adam',24,NULL})
user956584
  • 5,316
  • 3
  • 40
  • 50