I'm using this MySQL plugin for Node.js. Here's a very simple query:
db.query("SELECT * FROM user WHERE first = ? AND last = ?", [req.query.first, req.query.last], function(error, results) {
console.log(results);
});
Now here's the problem: what if only some of the query parameters are defined, but not all of them? This is a very common use case, so I'm guessing there is an elegant way to account for this, but this is all I can seem to come up with:
var query;
if (first && !last) {
query = "SELECT * FROM user WHERE first = ?";
} else if (!first && last) {
query = "SELECT * FROM user WHERE last = ?";
} else if (first && last) {
query = "SELECT * FROM user WHERE first = ? AND last = ?";
}
db.query(query, [req.query.first, req.query.last], function(error, results) {
console.log(results);
});
Writing a separate query for every possible combination is obviously a crude way to do it, and really isn't very practical if there are more than just a couple query parameters. Is there a more elegant (i.e. concise) way to account for an unknown number of null parameters?
UPDATE
This is what ended up working for me:
db.query("SELECT * FROM user WHERE (:first IS NULL || first = :first) AND (:last IS NULL || last = :last)", {first: req.query.first, last: req.query.last}, function(error, results) {
console.log(error);
});
This may be a bit cumbersome but you can use this query:
query = "SELECT * FROM user WHERE (? IS NULL || first = ?) AND (? IS NULL || last = ?)";
Just be sure at least one parameter is not null (either in the query or in js).
ETA: If you use the named parameter format (:param instead of ?) this will save you some repetition as well.