Sam Farmer

Growing up I never imagined I would play bass guitar for the Dave Matthews Band. And indeed it never happened.

10 Little Ones: For in loop for Queries (#2)

March 7, 2012

ColdFusion 10, now in public beta, adds for-in loops for query recordsets. The variable name in the for loop will reference each column by the column name.

The currentrow can be referenced by queryname.currentrow as seen in the example below. Same for recordcount. getArt = new query( sql="SELECT artName, price FROM Art" ).execute().getResult(); for ( row in getArt ) { writeOutput( "<li>" & getArt.currentRow & ": " & row.artName & " " & row.price & "</li>"); }

5 Comments

That's one of the best looking snippets of code I've seen since I first saw jQuery in action! (Yeah, I know it's cfscript!) Very compact indeed and still easy to see what it does at a glance. Can any other server side language do the same with less code?

By: Gary F 03/08/2012 7:30 AM
@Gary: Yes its very nice. I love both ColdFusion and jQuery for their simplicity and conciseness.

By: Sam Farmer 03/10/2012 10:36 AM
Awesome! I have been getting pretty sick of looping through queries in cfscript, with the same verbose "for (;;)" loops: for (var = i ; i <= getArt.recordCount; i++) { writeOutput( "<li>" & i & ": " & getArt.artName[i] & " " & getArt.price[i] & "</li>"); } A lot more work that way, what with having to manually keep track of your position in the recordset and explicitly referencing the row index. Still not really digging the cfscript version of cfquery, but oh well.

By: Jake Feasel 03/19/2012 5:32 PM
Some comments have been lost over the years due to moving hosts.

More


More blog entries that I have written.

Code coloring by PRISM.