 |

The following best practices for building ColdFusion applications have a significant impact on both speed and security.
Cache queries on high-traffic pages.
It's easy to do, just add the attribute cachedwithin="#createTimeSpan(0,1,0,0)#" to the cfquery tag to refresh the query every hour. For example:
<cfquery name="description" datasource="#request.dsn#" cachedwithin="#createTimeSpan(0,1,0,0)#">
SELECT description
FROM products
WHERE product_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.product_id#">
</cfquery>
If you need to force the query to refresh after making a change to the data, just run a cfquery containing the exact same SQL statement (including whitespace) with the attribute cachedwithin="#createTimeSpan(0,0,0,-1)#".
Note this example also uses the Request scope for storing the name of the data source. Setting this value in the Request scope makes it available inside custom tags, and avoids the locking issues associated with shared scopes like Session.
Use cfqueryparam to place dynamic values inside your queries.
This is one of the most important things you can do for the security of your application. It keeps malicious SQL Server code from being submitted through URL strings or form fields, plus it runs faster than just putting the variable between pound signs. Here is an example of passing an integer to a query:
SELECT description
FROM products
WHERE product_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.product_id#">
The following example also passes a string to the query, setting the value in the database to NULL if the string is empty:
UPDATE products
SET description = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.description#" null="#yesNoFormat(trim(form.description) EQ '')#">
WHERE product_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.product_id#">
|