1

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));
    }
});

3 Answers 3

2

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

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

7 Comments

But I don't want a string... It needs to be something like this (12,2,14) so I can use it in a query: SELECT question,answer FROM Game where ID in (12,2,14);
You want a string, what do you think the query string is? It's a string. WHERE id IN (" + conexao_bd.escape(a).join(", ") + ") ...."
You can't use join after escape. After you use escape on array it's no longer an array.
Docs say "Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'", so maybe all you are missing are the parentheses.
Array.prototype.join() Joins all elements of an array into a string. Source
|
2

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));
 }
});

Comments

1

There is an error on query

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

should be

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

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.