Node-MySQL - Escaping in Query() Method vs Mysql.Escape() / Mysql.EscapeId()

Lloyd Banks picture Lloyd Banks · Aug 4, 2014 · Viewed 22.2k times · Source

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()?

Answer

go-oleg picture go-oleg · Aug 5, 2014

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) {
  // ...
});