Is it possible to construct a MySQL query dynamically from a JSON object with potentially empty values?
For instance, starting with an object like this:
{
"a": 1
"b": ""
"c": "foo"
}
we want to generate a query like the following (ignoring the empty value for "b") :
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 may be a duplicate question. However, I was hoping for a more SQL-oriented approach, possibly involving variables and IF statements.
Edit 2 : I have discovered a method (working in node.js API but should work similarly 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)
`
Please note that this code is not ready for use as-is; adjustments are needed to address potential injection vulnerabilities.