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?
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?
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.
});
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
usersWHERE 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.