Melixion
Melixion

Reputation: 517

Issues with CFQUERY scope

As far as I know

<cfquery name="groups">

is equivalent to

<cfquery name="VARIABLES.groups">

In my project, in different parts (inside different functions) there is a cfquery with the same names.

When there are a lot of requests, I started getting strange responses from REST API (Coldfusion) where there were different datasets.

Through experiments, I realized that if I declare a local variable before calling cfquery, this will solve the problem, since the answer will be written exactly to the function variable, and not to the global variable.

<cfset var groups = {} /> <cfquery name="groups">

This option works correctly in all test cases.

My question is: is it correct to declare a local variable for cfquery inside a function, or are there other approaches to avoid my problem?

Upvotes: 2

Views: 163

Answers (1)

Paul
Paul

Reputation: 1575

You should always use ( when in a function ):

<cfset var groups = {} /> 
<cfquery name="groups">

or

<cfquery name="local.groups">

You can also use the local scope when inside functions. Without the use of var you're effectively making a global variable. Using either var or local inside a function will protect you again over writing the variable outside the function.

Upvotes: 3

Related Questions