13

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?

2
  • 1
    ' where Gender IN (\'' + Info.Gender.join("', '") + \'')'; Commented Dec 16, 2015 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. Commented Dec 16, 2015 at 10:29

3 Answers 3

27

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 ], ...);
Sign up to request clarification or add additional context in comments.

Comments

2

You need single quotes in your query:

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

2 Comments

For future visitors, use escaping instead of this proposed answer.
will this escape user input? it seems dangerous
0

You can pass the Info.Gender as array too:

var myQuery = `SELECT uid FROM users where Gender IN (?)`
var arrayData = ['Male', 'Female']
connection.query(myQuery, [arrayData])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.