ampc
ampc

Reputation: 312

node-mysql Using array in query

I'm trying do a query using an array but having a parse error.

a - contains an array

Ex:[ 7, 26, 87, 65, 86, 23, 63, 69, 44, 61, 8, 79, 47, 88, 15, 17 ]

conexao_bd.escape(a) - escaped array

Ex: 7, 26, 87, 65, 86, 23, 63, 69, 44, 61, 8, 79, 47, 88, 15, 17

It needs to be in this format (7, 26, 87, 65, 86, 23, 63, 69, 44, 61, 8, 79, 47, 88, 15, 17), so I can use it in the query. Any help how to change format?

Code

conexao_bd.query("SELECT question, answer FROM ", conexao_bd.escape(tipo) + " WHERE id IN " + conexao_bd.escape(a) ,function(err, rows){

    if(err) console.log("Erro na query questions: "+err);
    else{
        perguntas.questions.push(rows);
        console.log(JSON.stringify(perguntas));
    }
});

Upvotes: 1

Views: 3544

Answers (3)

Joniras
Joniras

Reputation: 1336

I Actually found the correct Answer including Escaping (to prevent SQL Injection):

Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

so the correct way:

conexao_bd.query("SELECT question, answer FROM ? WHERE id IN ?",[tipo,[a]],function(err, rows){

  if(err) 
     console.log("Erro na query questions: "+err);
  else{
    perguntas.questions.push(rows);
    console.log(JSON.stringify(perguntas));
 }
});

Upvotes: 2

ampc
ampc

Reputation: 312

There is an error on query

conexao_bd.query("SELECT question, answer FROM ", 

should be

conexao_bd.query("SELECT question, answer FROM "+

Upvotes: 1

Chris
Chris

Reputation: 1611

Look into Array.join() to return it as a string. This is a basic javascript question, not node related.

Upvotes: 2

Related Questions