Skip to content
Advertisement

How to append values of an array to an SQL statement in Javascript

let todo = [1, 2, 3, 4, 5, 6, 7, 8];

var stmt = "SELECT * FROM MY_USERS WHERE USER_ID = ?";

connection.query(stmt, todo, function(err, row) {
});

connection.release();

I would like to SELECT * FROM MY_USERS WHERE the USER_ID could be any of the values in the array [1, 2, 3, 4, 5, 6, 7, 8].

Is there a way I could do this without iterating over the array, constructing a new string segment and concatenating it to a final query statement?

Thank you all in advance.

EDIT

I cannot tell the exact number of the array elements in advance, so SELECT * FROM MY_USERS WHERE USER_ID IN (?, ?, ?, ?, ?, ? ,? ,?) will not do.

Advertisement

Answer

let todo = [1, 2, 3, 4, 5, 6, 7, 8];
var stmt = `SELECT * FROM MY_USERS WHERE USER_ID IN (${todo.join(",")})`;
console.log(stmt); // your query

You can use template literals like this,In this way you wouldn’t have to bother about number of elements in array.See Array​.prototype​.join()

let todo = [1, 2, 3, 4, 5, 6, 7, 8];

var stmt = `SELECT * FROM MY_USERS WHERE USER_ID IN (${todo.join(",")})`;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement