2

I would like to submit a MySQL query that can be described something like "return all values from * if the id column matches any of the values in some array x."

Is there any way to use the entire contents of an array in a query in this way?

1
  • @Adshi yes this would be in NodeJS Commented Mar 5, 2014 at 16:30

2 Answers 2

12
var ids = [3, 4, 6, 8];
var query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';

Now query contains query that will return all rows with id that matches any of the value in ids array.

With mysql package you can issue this query like this:

var mysql = require('mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'admin',
  password : 'password'
});

// construct query
var ids = [3, 4, 6, 8];
var query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';

connection.connect();

connection.query(query, function(err, rows, fields) {
  if (err) throw err;

  console.log(rows) // log all matching rows.
});
Sign up to request clarification or add additional context in comments.

3 Comments

What if it's more than one field? e.g. id and name.
It doesn't work if ids were strings and had spaces in between
Also, you should use escaping with '?' (question marks) npmjs.com/package/mysql#escaping-query-values
-1

You can use the implode function in PHP to take an array and transform it into a string separated by commas like this:

"SELECT * FROM users WHERE user_id IN (" . implode(',', $array_of_user_ids) . ")"

This is assuming that your array looks like $array_of_user_ids = array(1, 2, 3, 4, ...).

EDIT: My apologies, I didn't see the part about this being a JavaScript array. Adshi has your answer.

1 Comment

This question is asking under NodeJS environment

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.