4

i would like to convert a javascript array ids = [ 378, 464 ] to an array that MySQL is successfully parsing.

My SQL query includes the array like this:

Do something WHERE id IN ("472", "467"). 

This query works in MySQL Workbench.

I am struggling to get the array in the needed structure. I tried the following javascript structures within my api but i cannot get it to work.

("378", "464")
[ 378, 464 ]
('472', '467')

MYSQL Error Message:

  code: 'ER_PARSE_ERROR',
  errno: 1064,
2
  • 1
    where do you hand over the query? Commented Sep 30, 2019 at 9:08
  • 1
    You should also consider prepared statements - here's a way to deal with this for a variable-length IN clause: stackoverflow.com/questions/327274/… Commented Sep 30, 2019 at 9:21

4 Answers 4

6

You could stringify a stringed value and join all values with comma.

var ids = [378, 464],
    formatted = `(${ids.map(v => JSON.stringify(v.toString())).join(', ')})`;

console.log(formatted);

Sign up to request clarification or add additional context in comments.

4 Comments

This results in the following query for me: '(\\\"378\\\", \\\"464\\\")' which ends up throwing parsing errors in mysql
as i aready askes, where do hand over this? please add the wanted format and why the string has escaped backslashes.
I am inserting this via ``` db.query(('DO something WHERE id IN ?'), [formatted]) your fix works with: db.query(('DO something WHERE id IN ' + formatted) Thanks!
had you have a look to the linked question in the above comment section?
4

You can use Array#join('", "') to convert the array into the string format you desire.

var list = ["123", "354"];

if (!list.length) {
  console.log("Empty");
} else {
  var query = `select * from table where id in ("${list.join('", "')}")`;
  console.log(query);
}

Comments

2

Try Array.prototype.toString()

console.log("(",["378", "464"].toString(),")",);

Comments

0

Try it: Use join in array ("${arrItems.join('","')}")

var arrItems = [1,2,3,4,5,6,7,8,9];
var strSql = `SELECT * FROM Example WHERE ID IN ("${arrItems.join('","')}")`;
console.log(strSql);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.