Exercise 3: Displaying the query result using the cfoutput tag

In CFML Basics, you learned that the ColdFusion cfoutput tag is an easy mechanism to display literal text and the contents of variables. Additionally, the cfoutput tag significantly simplifies displaying the results of queries. When used to display the results from a query, the cfoutput tag automatically loops through the record set for you. You simply specify the name of the query in the query attribute of the cfoutput tag:

<cfoutput query="TripResult">

All the code between the cfoutput start and end tags is the output code block. The output code block executes repeatedly, once for each row in the record set. However, if the query returns no rows, ColdFusion skips the code contained in the output code block.

<cfoutput query = "xxx">
	...output code block...
</cfoutput>

Displaying the column contents from the SQL statement

In CFML you surround variables with number signs (#) to display their contents using the cfoutput tag. You also use this approach with column names specified in the SELECT statement of a cfquery. For example, when you want to display the trip names from the SQL query, you use #tripName# within the output code block:

<cfoutput query="TripResult">
	#tripname# 
</cfoutput>

For additional information about using SQL with cfquery and cfoutput, see ColdFusion MX Developer’s Guide.

To display the query results:

  1. Modify the triplisting.cfm file by adding the highlighted code so that it appears as follows:
    <cfquery name="TripList" datasource="compasstravel">
    		SELECT trips.tripName FROM trips
    </cfquery>
    <html>
    	<head>
    		<title>Trip Listing</title>
    	</head>
    	<body>
    		<h1>Trip List</h1>
    		<cfoutput query="TripList">#tripName#<br></cfoutput>
    	</body>
    </html> 
    
  2. Save the file as triplisting.cfm in the my_app directory.
  3. View the triplisting.cfm page in a browser. The page lists all the trip names retrieved from the Compass Travel database.

Reviewing the code

The following table describes the code used to display the query result set:

Code

Explanation

<cfoutput query="TripResult"> #tripName#<br</cfoutput>

Output code block. Displays the value of the tripName column for each row in the result set from the "TripResult" query.