12

I need to make MySQL query using "WHERE IN". This is my query:

var myQuery = 'SELECT uid FROM ' +tableName+ ' where Gender IN (' + Info.Gender.join() + ')';

If i print Info.Gender it will be ['Male', 'Female'], as a string. but when the query is done it says

SELECT uid FROM appUsers where Gender IN (Male, Female)

But should be:

SELECT uid FROM appUsers where Gender IN ('Male', 'Female')

That means it takes the Female not as a string.

Any ideas?

Dan The Man
  • 1,835
  • 6
  • 30
  • 50
  • 1
    `' where Gender IN (\'' + Info.Gender.join("', '") + \'')';` – fuyushimoya Dec 16 '15 at 10:24
  • 1
    When you're generating SQL in javascript, it's smart to always use double quotes, so you can be sure that any single quotes will be part of the SQL and not of the javascript. – SWeko Dec 16 '15 at 10:29

2 Answers2

25

You should use query escaping (provided that you're using node-mysql):

var myQuery = 'SELECT uid FROM ?? where Gender IN (?)';
connection.query(myQuery, [ tableName, Info.Gender ], ...);
robertklep
  • 198,204
  • 35
  • 394
  • 381
2

You need single quotes in your query:

var myQuery = "SELECT uid FROM " +tableName+ " where Gender IN ('" + Info.Gender.join("','") + "')";
Clay
  • 4,700
  • 3
  • 33
  • 49