Today a coworker was frustrated over a problem that seems like it should work.
He was using a SQL string and using that inside a CFQUERY like so:
<cfset sqlString = “SELECT id, name FROM users WHERE name = ‘John’ ” />
<cfquery name=”myQuery” datasource=”myDsn”>
#sqlString#
</cfquery>
This looks like it should work but it doesn’t. Any single quote will be changed to two single quotes so when the query actually executes, the query looks like this:
SELECT id, name FROM users WHERE name = ”John”
At first glance it looks like John is surrounded by double quotes but it’s not. It’s surrounded by two single quotes.
This obviously throws an error complaining about the double single quotes.
The solution is to replace the double single quotes with a single quote like so:
<cfquery name=”myQuery” datasource=”myDsn”>
#ReReplace(sqlString, “””, “‘”, “all”)#
</cfquery>
It’s hard to see what’s going on so I’ll expand the replace code
#ReReplace(sqlString, “””, “‘”, “all”)#
Note that the double single quotes are surrounded by double quotes and the single quote is surrounded by double quotes.
We are passing sqlString to the ReReplace function and telling it to find all double single quotes and replacing them with single quotes.
Voila! It works!
Hope this saves someone from pulling out their hair trying to figure out why it’s not working.