ColdFusion

ColdFusion Query Parameter Weirdness

You can file this one under either “huh, that’s kinda cool” or “that’s terrible…don’t ever do it!”…or maybe both.

As of ColdFusion 9, it’s now possible to execute queries in 100% cfscript. This is awesome for me ‘cuz I just happen to prefer to do as much in cfscript as possible.

Anyway, if you’ve worked with the cfscript version of cfquery, you’ll know that mimicking the behavior of cfqueryparam is pretty straightforward. Something like the following should do the trick:

     // create new query services
     qs = new query();
     // set attributes of service
     qs.addattributes(datasource="mydb",name="thequery");
     // set sql
     qs.setsql("select title from posts where isawesome = ?);
     // set queryparam for dynamic query
     qs.addparam(value="Awesome",cfsqltype="varchar");
     ...rest of processing...

Easy enough. I got to wondering if it would be possible to use a ternary operator as the “value” of the queryparam. Turns out, you can 🙂

     // set queryparam for dynamic query using ternary operator
     qs.addparam(value=form.isawesome==true ? 'Awesome' : '',cfsqltype="varchar");

Here, if a form variable (“isawesome”) is set to true, the value of the parameter will be “Awesome”; otherwise, it will be set to empty string.

I’m not sure how I feel about this. On a certain level, it’s cool that it works. However, it feels kind of hacky to More >