views:

65

answers:

1

I am trying to build a dynamic sql statement with this line

<cfset SQL = "SELECT url, MONTH(event_date) AS months, YEAR(event_date) AS year, event_date, title from events where title LIKE '%#form.event_name#%' ">

<cfquery name="results" >
#SQL#
</cfquery>

Seems there is a problem with the like clause. Any ideas? Do I need to escape the %?

Thanks

+6  A: 

Within a CFQUERY, ColdFusion will replace single quotes in #SQL# with double quotes automagically.

So in theory you would have to write your query like this:

<cfquery name="results" >
#PreserveSingleQuotes(SQL)#
</cfquery>

BUT... It's very dangerous to accept a form variable and use it without further validation directly in your query. Seems like an invitation for SQL injection attacks to me.

I'd rather use <cfqueryparam> like so:

<cfquery name="results" >
SELECT url, MONTH(event_date) AS months, YEAR(event_date) AS year, event_date, title 
from events 
where title LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%#form.event_name#%"> 
</cfquery>
Andreas Schuldhaus
Also, if you need to build the query dynamically and are running CF9, you can use the query function. http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSe9cbe5cf462523a0693d5dae123bcd28f6d-7ffb.html Using this you can insert a question mark into the query in place of your variable and use the addParam method.
Tyler Clendenin
Thank you for pointing this out!
Andreas Schuldhaus