Is there a way to dynamically build a MySQL query from a JSON object whose values are likely to be empty.
For example, from an object like this one:
{
"a": 1
"b": ""
"c": "foo"
}
create a query like this one ("b" is empty, it should not be taken into account) :
SELECT * FROM db.table
WHERE a = 1
AND c = "foo"
or
SELECT * FROM db.table
WHERE a = 1
AND b = ????
AND c = "foo"
Edit : it's probably duplicate indeed. But I thought there was a more SQL way to do that, for exemple using variables and IF statements.
Edit 2 : I found a way (working in node.js API but it should be similar in other languages) :
const jsonObj = {
"a": 1,
"b": "",
"c": "foo"
}
const query = `
SELECT * FROM db.table
WHERE
IF('${jsonObj.a}' != '', a = '${jsonObj.a}', 1=1)
AND
IF('${jsonObj.b}' != '', b = '${jsonObj.b}', 1=1)
AND
IF('${jsonObj.c}' != '', c = '${jsonObj.c}', 1=1)
`
Of course this code is not usable as it stands, it has to be adapted keeping in mind injection problems.