cfloop: looping over a query

Description

A loop over a query executes for each record in a query record set. The results are similar to those of the cfoutput tag. During each iteration, the columns of the current row are available for output. The cfloop tag loops over tags that cannot be used within a cfoutput tag.

Syntax

<cfloop 
  query = "query_name"
  startRow = "row_num"
  endRow = "row_num">
</cfloop> 

See also

cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfoutput, cfswitch, cfthrow, cftry

History

New in ColdFusion MX: On Windows, if the cfdirectory tag action = "list", the cfdirectory tag does not return the directory entries "." (dot) or ".." (double dot), which represent "the current directory" and "the parent directory." (In earlier releases, ColdFusion returned all the entries.)

CFML code such as the following, which was acceptable in ColdFusion 5, may cause incorrect output in ColdFusion MX:

<cfdirectory action = "list" directory ="c:\" name="somename">
Files in c:\<br>
<cfloop query = "somename" startrow = 3>
  #name#<br> >

For more information, see "cfdirectory".

Attributes

Attribute Req/Opt Default Description
query
Required
 
Query that controls the loop.
startRow
Optional
 
First row of query that is included in the loop.
endRow
Optional
 
Last row of query that is included in the loop.

Example

This example shows a cfloop looping over a query the same way as a cfoutput tag that uses the query attribute:

<cfquery name = "MessageRecords" 
  dataSource = "cfsnippets"> 
    SELECT * FROM Messages 
</cfquery>
<cfloop query = "MessageRecords"> 
  <cfoutput>#Message_ID#</cfoutput><br>
</cfloop>

The cfloop tag also iterates over a record set with dynamic start and stop points. This gets the next n sets of records from a query. This example loops from the 10th through the 20th record returned by MyQuery:

<cfset Start = 10> 
<cfset End = 20> 
<cfloop query = "MyQuery" 
  startRow = "#Start#" 
  endRow = "#End#"> 
  <cfoutput>#MyQuery.MyColName#</cfoutput><br>
</cfloop>

The loop stops when there are no more records, or when the current record index is greater than the value of the endRow attribute.

The advantage of looping over a query is that you can use CFML tags that are not allowed in a cfoutput tag. The following example combines the pages that are returned by a query of a list of page names into one document, using the cfinclude tag.

<cfquery name = "GetTemplate" 
  dataSource = "Library"
  maxRows = "5"> 
  SELECT   TemplateName 
  FROM Templates 
</cfquery> 
<cfloop query = "TemplateName"> 
  <cfinclude template = "#TemplateName#"> 
</cfloop>

Comments