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 number" 
    endRow = "row number"> 
</cfloop>

See also

cfabort, cfbreak, cfcontinue, cfexecute, cfexit, cfif, cflocation, cfoutput, cfswitch, cfthrow, cftry; For more information, see cfloop and cfbreak in the Developing ColdFusion Applications

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

<cfquery name = "MessageRecords" dataSource = "cfdocexamples">  
    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 fifth through the tenth record returned by the MessageRecords query:

<cfset Start = 5>  
<cfset End = 10>  
<cfloop query = "MessageRecords"  
    startRow = "#Start#"  
    endRow = "#End#">  
<cfoutput>#MessageRecords.Message_ID#</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 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 = "GetTemplate">  
    <cfinclude template = "#TemplateName#">  
</cfloop>