Introduction to ColdFusion Markup Language, concluded - Query Loop
(Page 2 of 6 )
This kind of loop will iterate over a Recordset (covered in Chapter 2). However, in this example we will create a simple query, loop over the query, and then output each employee in the database. Create a new file in the cfbook site and enter the following code (queryloop.cfm):
<cfquery name="getEmployees" datasource="CompanyInfo">
SELECT
*
FROM
Employee
</cfquery>
<cfloop query="getEmployees">
<cfoutput># getEmployees.FirstName# # getEmployees.LastName#<br /></cfoutput> </cfloop>
In this code, you begin by creating a query using the<cfquery>element, which contains SQL code between the opening and closing tags. Then you call the<cfloop>tag and pass it the name of the query from the<cfquery>tag.
When looping over a query, each iteration of the loop returns the next record from the Recordset. So, the preceding code grabs all employees from theCompanyInfodatabase and outputs each employee's name in the browser window, as shown in Figure 3-11. When looping over queries, ColdFusion automatically exits the loop once the end of the records is reached. Using <cfloop>rather than<cfoutput>to loop over a query can be very advantageous--especially when you want to loop over one recordset inside of a loop over another recordset. You cannot nest<cfoutput> query loops over different queries inside each other, but you can do this with<cfloop>.

Figure 3-11. The result of using a query loop to output each employee name from the Employee table
List Loop
Looping over a list can be very useful in many circumstances. A list is nothing more than a string containing one or more items delimited by a set character, usually a comma. For example, you could loop over a list of menu links to create a dynamic menu. Enter the following code into a new ColdFusion document in Dreamweaver (listloop.cfm):
<cfloop list="home,tutorials,forum,articles,contact" index="currentLink">
<cfoutput><a href="#currentLink#.cfm">#currentLink#</a><br /></cfoutput>
</cfloop>
Test the code. For each item in the list, you are outputting a link to the browser window, as you can see in Figure 3-12.

Figure 3-12. Using a list loop to create a simple list menu
TIP When building lists, dont put a space after the comma. Doing so will insert a space before each item in the list. |
Also note that the<cfloop> "delimiter" attribute will allow you to specify some character other than a comma to use as the list entry separator.
Next: Collection Loop >>
More ColdFusion Articles
More By Apress Publishing
|
This article is excerpted from chapter three of the book ColdFusion Web Development with Dreamweaver MX 2004, written by Jen and Peter deHaan et al. (Apress; ISBN: 1590592379). Check it out today at your favorite bookstore. Buy this book now.
|
|