Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic SQL in CFScript

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?

like image 671
Mohamad Avatar asked Mar 02 '26 03:03

Mohamad


1 Answers

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();
like image 77
Adam Tuttle Avatar answered Mar 04 '26 18:03

Adam Tuttle