Adobe ColdFusion 8

Working with queries and data

The ability to generate and display query data is one of the most important and flexible features of ColdFusion. The following sections describe more about using queries and displaying their results. Some of these tools are effective for presenting any data, not just query results.

Using HTML tables to display query results

You can use HTML tables to specify how the results of a query appear on a page. To do so, you put the cfoutput tag inside the table tags. You can also use the HTML th tag to put column labels in a header row. To create a row in the table for each row in the query results, put the tr block inside the cfoutput tag.

In addition, you can use CFML functions to format individual pieces of data, such as dates and numeric values.

Put the query results in a table

  1. Open the ColdFusion actionpage.cfm page in your editor.
  2. Modify the page so that it appears as follows:
    <html>
    <head>
    <title>Retrieving Employee Data Based on Criteria from Form</title>
    </head>
    
    <body>
    <cfquery name="GetEmployees" datasource="cfdocexamples">
        SELECT FirstName, LastName, Salary
        FROM Employee
        WHERE LastName=<cfqueryparam value="#Form.LastName#" 
        CFSQLType="CF_SQL_VARCHAR">
    </cfquery>
    <h4>Employee Data Based on Criteria from Form</h4>
    <table>
    <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Salary</th>
    </tr>
    <cfoutput query="GetEmployees">
    <tr>
    <td>#FirstName#</td>
    <td>#LastName#</td>
    <td>#Salary#</td>
    </tr>
    </cfoutput>
    </table>
    <br>
    <cfif IsDefined("Form.Contractor")>
        <cfoutput>Contractor: #Form.Contractor#</cfoutput>
    </cfif>
    </body>
    </html>
    

  3. Save the page as actionpage.cfm in the myapps directory.
  4. View the formpage.cfm page in your browser.
  5. Enter Smith in the Last Name text box and submit the form.

    The records that match the criteria specified in the form appear in a table.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<table>

Puts data into a table.

<tr> <th>First Name</th> <th>Last Name</th> <th>Salary</th> </tr>

In the first row of the table, includes three columns, with the headings: First Name, Last Name, and Salary.

<cfoutput query="GetEmployees">

Tells ColdFusion to display the results of the GetEmployees query.

<tr> <td>#FirstName#</td> <td>#LastName#</td> <td>#Salary#</td> </tr>

For each record in the query, creates a new row in the table, with three columns that display the values of the FirstName, LastName, and Salary fields of the record.

</cfoutput>

Ends the output region.

</table>

Ends the table.