0

My current query looks like this:

router.get('/search?', function(req, res, next) {
    var title = req.query.title;
    var sql = "SELECT * from users WHERE title = ?"; 
    connection.query(sql, [title], function (error, results, fields) {
        res.json({"status": 200, "error": null, "response": results});
    });
});

It works if I enter:

localhost:4001/api/v1/users/search?title=mr

But how can I search for multiple values with OR ... like this:

localhost:4001/api/v1/users/search?title=mr,mrs,dr
2
  • Are you planning to search for partial matches or full matches? Commented Feb 21, 2018 at 11:15
  • ... mmh ... I in this case full match Commented Feb 21, 2018 at 11:31

1 Answer 1

2

Basically,

If you have multiple comma separated values in a query parameter, you can split them by , and use the sql IN clause.

If you have a single parameter value then your method already works fine.

router.get('/search?', function(req, res, next) {
    var title = req.query.title;
    var sql;
    if (title.includes(",")) {
        var params = title.split(",");
        sql = "SELECT * from users WHERE title IN " + params;      
    } else {
        sql = "SELECT * from users WHERE title = " + title;      
    }
    connection.query(sql, function (error, results, fields) {
        res.json({"status": 200, "error": null, "response": results});
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

... is there any way to also bind it .... or is it fairly save like shown?
i did not quite get what you are saying.
Well ... isnt't ... sql = "SELECT * from users WHERE title = " + title; ... a bit unsafe? ... and rather use placeholders '?' ? w3schools.com/nodejs/…

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.