Home > Software design >  I need to convert a javascript array to a sql list
I need to convert a javascript array to a sql list

Time:10-01

so i have this req -

app.delete("/delete/:sku", (req, res) => {
const sku = req.params.sku;
db.query(DELETE FROM products WHERE sku IN(?)

the console.log(req.params.sku) results in - wefwefwef,erferferfrgrwb,23r23r on the console,

i need to convert the sku string to a SQL list so i can insert the values for the IN clause.

CodePudding user response:

You should use a parameterized query. This could look something like this.

const sku = req.params.sku.split(',');
const ins = new Array(sku.length).fill('?').join();
db.query(`DELETE FROM products WHERE sku IN (${ins})`, sku);

If you need to give the params names like @p1, then something like this

const sku = req.params.sku.split(',');
const ins = sku.map((_, i) => `@p${i}`).join();
db.query(`DELETE FROM products WHERE sku IN (${ins})`, sku);
  • Related