Skip to main content
Known Participant
October 26, 2010
Answered

How to populate a table with array loop

  • October 26, 2010
  • 2 replies
  • 853 views

I'm looping an array object and as I loop, I'm calling a function and this function returns 6 items

<CFLOOP  from="1" to="#ArrayLen(zz)#" index="k">

  <cfdump var="#zz.getLine()#"> <p>

</CFLOOP >

The above cfdump will return something like:

[empty string]

street name1

[empty string]

[empty string]

city1

state1

zip1

[empty string]

street name2

Apartment AA

[empty string]

city2

state2

zip2

street name 3

Margenthaller Hall

Suite 202

city2

state2

zip2

etc

I need to insert these results into my address table while looping.

When I did the following (see below), each record got repeated 12 times (not sure why)

<CFLOOP  from="1" to="#ArrayLen(zz)#" index="k">  <cfdump var="#zz.getLine()#">

  <cfquery name="test" datasourece="MyDNS">

   INSERT INTO MyAddr (street1,street2,street3,city,state,zip)

   VALUES ('#zz[1].getLine()#', '#zz[2].getLine()#', '#zz[3].getLine()#', '#zz[4].getLine()#','#zz[5].getLine()#', '#zz[6].getLine()#')

</cfquery>

</CFLOOP >

Is there a way? to do insert as I already got the address correctly while looping but not sure how can I use the return result in insert statement.

Can anyone help?

  

This topic has been closed for replies.
Correct answer Dan_Bracuk

Where did this array come from in the first place?

2 replies

Dan_BracukCorrect answer
Inspiring
October 26, 2010

Where did this array come from in the first place?

ilssac
Inspiring
October 26, 2010

For what you seem to be doing here, the loop is unnecessary and causing the multiple inserts since the <cfquery...> is inside the insert, it will be executed for each and every iteration of the loop.

You COULD put the loop inside the <cfquery...> to build the repeating part of your query I.E. the VALUES clause it seems in your case.  But, unless you would have different sized arrays I would just do what you are doing and explicitly calling each array element.  I.E. the zz[1]...zz[2]...zz[3]...etc. that you have.

aleckenAuthor
Known Participant
October 29, 2010

Thank you thank you!!