I need to add if conditions to my SQL query. I came up with this solution, but it does not work, and I'm not sure why.
local.platformId = arguments.platformId ? "AND platforms.id = #arguments.platformId#" : "";
local.pages = new Query(dataSource=variables.wheels.class.connection.datasource);
local.pages.setSQL
("
SELECT COUNT(games.id) AS totalRecords
FROM games
INNER JOIN platforms ON games.platformId = platforms.id
WHERE 0=0
:platform
");
local.pages.addParam(name="platform", cfsqltype="CF_SQL_VARCHAR", value=local.platformId);
local.pages = local.pages.execute().getResult();
I get an error of: You have an error in your SQL syntax; check ... near ''AND platforms.id = 1' ''' at line 6
Any idea how to get around this limitation and still ensure safety from SQL injection?
I like using savecontent for this:
savecontent variable="local.sql"{
WriteOutput("
SELECT COUNT(games.id) AS totalRecords
FROM games
INNER JOIN platforms ON games.platformId = platforms.id
WHERE 0=0
");
(arguments.platformId)
? WriteOutput("AND platforms.id = :platform")
: WriteOutput("");
}
local.pages = new Query(dataSource=variables.wheels.class.connection.datasource);
local.pages.setSQL(local.sql);
if (arguments.platformId){
local.pages.addParam(name="platform", cfsqltype="CF_SQL_VARCHAR", value=arguments.platformId);
}
local.pages = local.pages.execute().getResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With