Apostrophe Issues in an Update Query

Coldfusion Code Tip…

When things are frustrating, and have a simple solution, I like to share.

When you are a doing a data update, you will often have a text field in a form that will bring an apostrophe with it. For example, if I am collecting business information, I could have a visitor enter their company name. The name might be Amy’s Gems. If I do a sloppy insert statement like the one below, the query will fail.
<cfquery datasource="#application.dsn#">
UPDATE customers
SET companyName='#form.companyName#'
WHERE id=#recordID#
</cfquery>

If you are allowing your users to update or insert their own data, this will error out (with IIS and MS SQL DB running CF8) when your user includes an apostrophe in the field.

You can avoid this by enclosing your values in a cfqueryparam. In fact, getting into the habit of using cfqueryparam in every instance will be a much more secure method and will reduce your exposure to malicious attacks such as a SQL injection hack.

The above query would now look like…
<cfquery datasource="#application.dsn#">
UPDATE customers
SET companyName=<cfqueryparam value="#form.companyName#" cfsqltype="cf_sql_varchar">
WHERE id=<cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
</cfquery>

Happy coding. This simple fix might keep someone from pulling their hair out. You can avoid all kinds of cfreplace and cfset statements and end up with an app that is more secure.

Leave a Reply

Your email address will not be published.