6

i need to do a multiple row delete query with the where clause in list (id1,id2..) But since we don't have lists in JS i'm having a problem with passing the parameters to the query.This is my code:

 let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 connection.query(Query,list, function (err, result) {
     `enter code here`
 };

when i pass it this way and after logging the mysql server to a Logfile i see that it actually passes only the first id.

PS : i tried without the parentheses around ? and also doing a Array.join on the list but both didn't work.

2
  • This is similar to stackoverflow.com/questions/41935358/in-clause-in-mysql-nodejs As @hoangdv wrote, you need to pass all the parameters as array. Commented Feb 19, 2020 at 12:40
  • ? is simply broken for use with arrays, sad but true. Just interpolate in the array - and it's up to you to avoid injection. Commented May 25 at 18:41

3 Answers 3

7

Read in document of https://github.com/mysqljs/mysql#performing-queries (if you use this lib to connect mysql)

 let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 // values param need is a array of value to binding to "?"
 // you can try [list.toString()] if the block above not working
 connection.query(Query,[list], function (err, result) {
     `enter code here`
 };
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I want. Works well in node mysql2 package
0

Simply append the list of items to the query string:

 let list = [1, 2, 3];
 let Query = `DELETE FROM Table WHERE id IN (${list})`;
 connection.query(Query, function (err, result) {
     `enter code here`
 };

2 Comments

good as long as the list variable is not filled in with data from outside the system, e.g. user inputted data. Otherwise, SQL injection would be a problem.
There's a reason why MySQL says to "always escape your data". You don't want to find it out
0

Unfortunately, ? placeholders don't work with the IN operator. So you should escape the values. Say the list variable is coming from an external source; so to prevent SQL Injection you can:

// `list` is filled in outside this process
const Query = `DELETE FROM Table WHERE id IN (${list.map((item) => connection.escape(item))})`;
connection.query(Query, function (err, result) {
  // handle error or result here
};

I noticed that list.map(connection.escape) won't work and throw: TypeError: Cannot read property 'config' of undefined

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.