MeanDean73
MeanDean73

Reputation: 43

Variable cfform values - nested pound sign

I am having trouble with a problem. I am using cfoutput to run the results of a query inside a form. There are a few cfselects that are dynamically named, i.e. entry_1, entry_2, etc. These are then passed to an actionpage alonge with the record count in the url, where I want to insert them into a database with a cfloop.

<cfloop from="1" to="#url.Count#" index="i">  
<cfquery name="id_#i#" datasource="xxx">Insert Into table1(entry_level) Values(#form.entry_#i##)</cfquery>  
</cfloop>  

And it's tossing an error everytime. I've tried using array format, but I still can't get it to work. Please help!

Upvotes: 4

Views: 339

Answers (1)

Brian Hoover
Brian Hoover

Reputation: 7991

You can't construct a dynamic struct selector that way. You can do something like the following to get the same result.

So, using the following data:

<cfset url.count = 3>
<cfset form.entry_1 = 1>
<cfset form.entry_2 = 2>
<cfset form.entry_3 = 3>

Something like this would work -

<cfloop from="1" to="#url.Count#" index="i">  
  <cfquery name="id_#i#" datasource="xxx">
    Insert Into table1(entry_level) Values(#form['entry_' & i]#)
  </cfquery>  
</cfloop>  

ColdFusion basically gives you two ways to access a value of a structure, either via a . notation or via brackets. If you are trying to access a structure via a dynamic key, you have to use brackets.

By the way, slightly better would be:

   <cfloop from="1" to="#url.Count#" index="i">  
      <cfquery name="id_#i#" datasource="xxx">
        Insert Into table1(entry_level) Values(<cfqueryparam value="#form['entry_' & i]#">)
      </cfquery>  
    </cfloop>  

cfQueryParam automatically escapes the entry so that you don't have to worry about SQL injection attacks. It can also make the query slightly more efficient.

Upvotes: 10

Related Questions