1

I'm trying to query mysql database with where clause as below.

Here popularTopicsNames is a dynamic array and its length and elements varies.

var scoreQuery=connection.query('SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN ('+popularTopicsNames+')', function(err,result,fields){
if(err) throw err;
else{
    console.log(result);
    }

2 Answers 2

2

If it's just an array then you're trying to pass it as a string, which won't work.

Try

var scoreQuery = connection.query("SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN ('" + popularTopicsNames.map(mysql.escape).join("','") + "')",
    function(err, result, fields) {
        if (err) {
            throw err;
        } else {
            console.log(result);
        }
    });
Sign up to request clarification or add additional context in comments.

4 Comments

You're missing the beginning and end single quotes right inside the parenthesis. Without them you'll end up with invalid SQL for more than 1 item in the array. Example: SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN (foo','bar)
Also, if the topic names are user submitted, then they should be properly escaped first to prevent SQL injection attacks.
I think you need something like popularTopicsNames.map(mysql.escape).join("','") instead.
@mscdex You're right, as the escape return value wraps it in quotes.
1

This will solve the issue in a more readable way.

var scoreQuery = connection.query(`SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN (?)`, [popularTopicsNames],
(err, result, _fields) => {
    if (err) {
        throw err;
    } else {
        console.log(result);
    }
});

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.