Reputation: 21
I'm making a survey of sorts and for one part I loop through all the questions, cfquery and then use the query as a variable. It looks something like this:
<cfloop index="q_number" from="1" to "10">
<cfquery name="q#q_number#_check" datasource="datasource">
SELECT *
FROM table
</cfquery>
<cfif len(#q#q_number#check.something#) GT 0>
I get an error because of the variable inside of the variable. Is there a quick hack around this? I tried doing
<cfset escape_var = q#q_number#_check.question>
<cfif len(#variables.escape_var#) GT 0>
but that didn't work.
Thank you.
Upvotes: 2
Views: 1239
Reputation: 61
if you are not getting anything special within the loop, then why have the query there at all? Could you not just use a single query. if you are using a where clause then use a query of queries inside your loop to get the other information.
<cfquery name="myquery" datasource="ds">
select * from mytable
</cfquery>
<cfset myquestions = arrayNew(1)>
<cfloop index="q_number" from="1" to "10">
<cfquery name="myotherquery" dbtype="query">
select * from myquery
where question = #q_number#
</cfquery>
<cfif myotherquery.something GT 0>
<cfset myquestions[q_number] = myotherquery.something>
</cfif>
Unless you need the results of the query inside your loop somewhere outside of the loop, you dont need a dynamic query name. Each time through the loop, the name will be overwritten.
I would just setup an array to store my loop results then i can use them later without the need to have 10 identical queries.
Hope that helps some Tim
Upvotes: 0
Reputation: 15474
You can use evaluate to save the query to a variable and then use it like you normally would.
<cfset resolved_query = evaluate("q#q_number#_check")>
<cfif len(resolved_query.something) GT 0>
Upvotes: 0
Reputation: 28873
q#q_number#check.something
The query is placed in the variables scope which means you can use array notation to access it. This works in CF9. Though you may need to add a [rowNumber] for CF8.
<cfif len(variables["q#q_number#_check"].something) GT 0>
But you really should avoid querying within a loop. If you could elaborate on the requirements, we could suggest some better alternatives.
Upvotes: 3
Reputation: 1
Is the IF inside your look? if that is the case there is no need to have your query dynamically named.
If you need it out side of the look I would recommend sticking the results set in an array.
<cfset checkArray = arrayNew()>
<cfloop index="q_number" from="1" to "10">
<cfquery name="q_check" datasource="datasource">
SELECT *
FROM table
</cfquery>
<cfif len(q_check.something) GT 0>
</cfif>
<cfset arrayAppend(checkArray,qcheck)>
</cfloop>
<cfif len(checkArray[1].something) GT 0>
</cfif>
You may have to play around with the IF statement to get the results your looking for but that should get you headed down the right track.
Upvotes: 0