0

I'm new to Node.js and don't know how sql injection gets handled? My code in Node.js is something like below:

connection.query('SELECT email FROM users WHERE firstName LIKE \'%'+firstName+'%\';', function (error, rows, fields){ someCodeHere... }

I receive inputs directly from user and put it inside of the query. I'm more concerned about sql injection here? Does Node.js do the sanitization? How to prevent sql injection in Node.js?


EDIT :
In the above link provided it's been said that we should use:

connection.escape(query);

Should I put it inside of another variable or my code should look like the below one:

connection.escape(query);
connection.query('SELECT email FROM users WHERE firstName LIKE \'%'+firstName+'%\';', function (error, rows, fields){ someCodeHere... }
Alireza
  • 6,497
  • 13
  • 59
  • 132

1 Answers1

3

I would recommend using ? placeholders which performs escaping.

var query = 'SELECT email FROM users WHERE firstName LIKE \'%?%\';';
connection.query(query, [firstName], function (error, rows, fields){
  //someCodeHere... 
});

Also, you may want to not set multipleStatements to true. It is false by default, but as noted in the readme, it is susceptible to SQL injections. Whether or not that is the case when input is escaped, I'm not sure.

multipleStatements: Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false)

Kevin Reilly
  • 6,096
  • 2
  • 25
  • 18
  • This code doesn't return anything! consle.log(myFetchedData) returns nothing. – Alireza Feb 28 '14 at 08:25
  • Hmm. Sorry, I'm not in a position to test presently. Are you sure the callback is being reached at all? – Kevin Reilly Feb 28 '14 at 08:51
  • By the way, unless this is used to show the emails of users with the same first name, this is likely not a safe approach query wise. – Kevin Reilly Feb 28 '14 at 08:53
  • displaying emails is just for demonstration here. I show their picture and put their id inside of a hidden element. – Alireza Feb 28 '14 at 09:08
  • I have updated my answer with the appropriate solution. The previous suggestion required additional [code](https://github.com/felixge/node-mysql#custom-format) – Kevin Reilly Feb 28 '14 at 09:16