The i-Technology Media!
Register | Log in
   
 
.NET  ·  AJAX  ·  CLOUD  ·  ECLIPSE  ·  FLEX  ·  OPEN WEB  ·  iPHONE  ·  JAVA  ·  LINUX  ·  OPEN SOURCE  ·  ORACLE  ·  PBDJ  ·  SEARCH  ·  SILVERLIGHT  ·  SOA  ·  VIRTUALIZATION  ·  WEB 2.0  ·  WIRELESS  ·  XML
Comments
Google Wave Invitation Giveaway
By Aditya Banerjee
Timo Hirvonen wrote: I would really appreciate an invitation. Been desperately trying to find one :) timo [dot] hirvonen [at] gmail [dot]com
Nov. 27, 2009 11:13 AM EST
Cloud Expo on Google News
Did you read today's front page stories & breaking news?


2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Cloud Computing & Enterprise IT: Cost & Operational Benefits
How and Why is a Flexible IT Infrastructure the Key To the Future?
Click For 2008 West
Event Webcasts

2009 East
GOLD SPONSORS:
CA
Get Your Transactions Under Control: SOA Performance Management
Software AG
Performance Driven Adoption: The Secret to Advancing SOA
Intel
The Evolving SOA Appliance: 3 Game-Changing Innovations
SILVER SPONSOR:
Denodo
Data Mashups: Deliver Your Project Faster with Virtualized Data Services Across Internal & External Sources
POWER PANELS:
The Business Value of Service Orientation
Driving Profitability Through User Experience
Click For 2008 West
Event Webcasts
Live Google News by SYS-CON!
Top Three Links You Must Click On


CF Basics
Creating Dynamic Websites With ColdFusion
The CF Apprentice SeriesPart 5 - Displaying Data With SQL

By: Michael Smith
Sep. 17, 2003 12:00 AM

In this article we continue to look at what ColdFusion is and how you can use it for dynamic website creation. We cover using SQL to dynamically retrieve and display data from any database along with testing and debugging techniques.

What is ColdFusion?
In case you missed the previous articles that introduced ColdFusion, let me explain what it is. ColdFusion, which was introduced by Allaire in 1995 and is currently on version 4.5.1, is a programming language based on standard HTML (Hyper Text Markup Language) that is used to write dynamic webpages. It lets you create pages on the fly that differ depending on user input, database lookups, time of day or any other criteria you dream up. ColdFusion pages consist of standard HTML tags such as <FONT SIZE="+2"> together with CFML (ColdFusion Markup Language) tags such as <CFQUERY>, <CFIF> and <CFLOOP>.

Creating a Page to Select and Display Data
To select and output data from a database, you create a ColdFusion application page that uses the CFQUERY tag, plus any HTML formatting you want. The database query is done with SQL (Structured Query Language, pronounced "sequel") inside the CFQUERY tag.

To illustrate, here is an example from a database called Company associated with an ODBC (Open DataBase Connectivity) data source named CompanyDB.

To create a select query called EmployeeList that retrieves all of the records in the Employees table, use this syntax:

EmployeeList.cfm


   <CFQUERY NAME="EmployeeList"
      DATASOURCE="CompanyDB">
      SELECT FirstName, LastName, PhoneNumber, Email
      FROM Employees
      ORDER BY LastName
   </CFQUERY>

SQL and ODBC
SQL is an industry standard language used to interact with relational databases. While the advanced features of SQL are extremely powerful, learning the basics of SQL is relatively simple. You can learn the basic SQL required to productively use ColdFusion in a few minutes.

The basic SQL statements are:
Action SQL syntax
Read records: SELECT FieldsList FROM TableName WHERE conditions ORDER BY FieldsList
Add Records: INSERT INTO TableName (FieldsList) VALUES (ValuesList)
Delete Records: DELETE * FROM TableName WHERE conditions
Change Records: UPDATE TableName SET field = value WHERE condition

No Need to Write SQL Statements by Hand
In practice, you rarely need to write SQL statements by hand since there are so many high-quality visual SQL tools available. Visual SQL tools include the Microsoft Access query builder or the Microsoft Query applet bundled with Microsoft Office. These tools allow you to visually define and preview queries and then copy and paste the resulting SQL statement into other applications such as ColdFusion. This will shield you from a lot of cryptic ODBC error messages and SQL syntax errors too!

ODBC is a way for programs such as ColdFusion to use the same SQL with different backend databases without having to change any code. The ODBC driver handles all the details of how to talk to the particular database used and you are free to spend more time on other issues such as the user interface. ODBC drivers are available for most databases including:

  • Access SQL server
  • Excel
  • Comma delimited text
  • HTML tables
  • FoxPro
  • Paradox
  • Oracle
  • Sybase
  • DB2

Displaying the Results of a Selection
Once you've created a CFQUERY in your application page file, you can then reference its results within other CFML tags. The query results can then be used to dynamically create an HTML page.

As you learn to use CFML tags in application page files, keep in mind that you can also use HTML tags and text in application page files. Wherever you use standard HTML tags and text inside your application page, ColdFusion simply passes the tags and text directly back to the client browser.

The most flexible way to display data retrieved from a CFQUERY is to define a CFML output section in your application page file using the CFOUTPUT tag. Output sections can be linked to a specific query or contain content from multiple queries.

Basic output sections have the following syntax:


     <CFOUTPUT QUERY="queryname" MAXROWS=n STARTROW=s>
        Literal text, HTML tags, and 
        dynamic field references (e.g., #FirstName#)
     </CFOUTPUT>

Note the use of the pound signs (#) to enclose the naked variable name FirstName. A CFOUTPUT tag can contain:

  • Literal text
  • HTML tags
  • References to query columns
  • References to dynamic parameters such as form fields
  • Functions

Example
If you execute a CFQUERY called EmployeeList and you want to use it to display the first name, last name, and e-mail address of each employee (separated by a horizontal rule), use the following CFOUTPUT section:

EmployeeList2.cfm


     <CFOUTPUT QUERY="EmployeeList">
        <HR>
        #FirstName# #LastName# 
        (E-mail: <A HREF="mailto:#Email#">#Email#</A>)<BR>
     </CFOUTPUT>

If there were three records in the query result set, the HTML generated by this CFOUTPUT section would look like this:


   <HR>
   Deborah Jones 
   (E-mail: <A HREF="mailto:dj@ibm.net">dj@ibm.net</A>)<BR>
   <HR>
   John Smith 
   (E-mail: <A HREF="mailto:js@ibm.net">js@ibm.net</A>)<BR>
   <HR>
   Frank Wilson 
   (E-mail: <A HREF="mailto:fw@ibm.net">fw@ibm.net</A>)<BR>

Notice the use of the standard HTML <A HREF="...> tag with the mailto: URL to give a live e-mail link on the page.

Presenting Query Output in a Table
Presenting the results of queries using CFOUTPUT sections is usually adequate if the number of records returned is small. However, you might need a more compact and structured display of query results. Because the CFOUTPUT tag can include any HTML, you can use standard HTML table tags to build a table dynamically. The result is a clear, concise rendering of your query results.

Let's change our above example to display it in a table:

EmployeeList3.cfm


   <TABLE>
      <TR>
      <TD>First Name</TD>
      <TD>Last Name</TD>
      <TD>E-mail</TD></TR>
   <CFOUTPUT QUERY="EmployeeList" MAXROWS=10>
      <TR>
      <TD>#FirstName#</TD>
      <TD>#LastName#</TD>
      <TD><A HREF="mailto:#Email#">#Email#</A></TD></TR>
   </CFOUTPUT>
   </TABLE>

This code would create a table with three columns labeled "FirstName", "Last Name" and "E-mail". The table would draw its data from the CFQUERY named "EmployeeList" and would display no more than 10 rows.


   <TABLE>
      <TR>
      <TD>First Name</TD>
      <TD>Last Name</TD>
      <TD>E-mail</TD>
      </TR>
      <TR>
      <TD>John</TD>
      <TD>Smith</TD>
      <TD><A HREF="mailto:js@ibm.net" js@ibm.net</A></TD> 
      <TR>
      ...
   </TABLE>

In your browser you should see something like:
First Name Last Name E-mail
Deborah Jones dj@ibm.net
John Smith js@ibm.net
Frank Wilson fw@ibm.net

Using Dynamic Parameters in SQL Statements
You can harness the real power of the CFQUERY tag by dynamically customizing the contents of the SQL attribute by using parameters passed to the application page. A SQL statement is customized by embedding dynamic parameters within the SQL text. Dynamic parameters (also called variables) normally include form entries, parameters passed in the URL, and CGI environment information.

The convention for including a dynamic parameter inside a SQL statement is to enclose it in pound (#) signs (e.g., #LastName#). Whenever ColdFusion sees text enclosed by # signs, it searches through all Form, URL, cookies, client, and CGI variables looking for one that matches the specified name. When it finds the name, it substitutes the appropriate value for the parameter reference. If you specify the variable type (Form) used in the following example less searching will have to be done and your code will run a bit faster.

Example of dynamic SQL
If you created a form to allow end users to search for employees by last name, you could use the following SQL statement with dynamic parameters:


   <CFQUERY NAME=&quot;EmployeeList&quot;
      DATASOURCE=&quot;CompanyDB&quot;>
      SELECT * FROM Employees 
      WHERE LastName = '#Form.LastName#'
   </CFQUERY>

If a user entered "Rucker" for LastName, the SQL statement sent to the database would be:


	SELECT * FROM Employees 
 	WHERE LastName = 'Rucker'

Sources for dynamic parameters
The following table summarizes the primary sources from which you can draw dynamic parameters for use in your SQL queries:
Field Description
Form fields The most common way of passing parameters to an application page. When a user enters data in a form field, a parameter bearing the name of the form field (#Form.formfield#) is passed to the application page.
URL parameters Parameters that are embedded on the end of a URL (such as, /input.cfm?name=adam).
Server A variable that remains available to all application pages until the ColdFusion application server terminates.
CGI environment An environment variable interpreted by the browser. Every request sent to an application page has several environment variables sent to it that relate to the context in which it was sent. The variables available depend on the browser and server software in use for a given request.
Query objects Query columns you can reference once a query has been executed. Once a query has been run, its results can be used as dynamic parameters in other queries. For example, a query that returns a column called UserID can be Referenced in the following form: queryname.UserID
Cookies General mechanism for storing and retrieving information about the Web client (browser)
Client variables Used to store persistent client variables in the system Registry on the Web server. These variables are specific to an individual browser accessing your ColdFusion application.
Session variables Variables available only for an individual session. Session Variables are tied to an individual client and persist for as long as that Client ID maintains a session.
Application variables Variables available only for an individual application. Application names are defined in the CFAPPLICATION tag, which is typically used in the application.cfm file.

Table 1 - Variable Types in CF

Testing and Debugging Applications

Summary
In this article we have looked at how to search a database using ColdFusion and SQL SELECT and how to display the results in a table. We also looked at dynamic queries and ColdFusion variable types that you can use in your pages.

Resources

Sams Teach Yourself SQL in 10 Minutes by Ben Forta
www.amazon.com/exec/obidos/ASIN/0672316641/

SQLServer 7.0 Books Online, download from the following Microsoft Web site:
http://download.microsoft.com/download/SQL70/File/2/Win98/En-US/SQLBOL.exe

 

Introduction to SQL
http://w3.one.net/~jhoffman/sqltut.htm

SQL Beginner's Tutorial
http://step.sdsc.edu/s96/sql/tutorial.html

Tutorial — Using Microsoft Access-SQL
www.cs.jcu.edu.au/Subjects/cp1500/1999/tutes/AccessSqlEx4-2.html

 

SQL Reference
http://nscpcw.physics.upenn.edu/db2_docs/db2s0/db2s003.htm

SQL Reference (Microsoft)
http://msdn.microsoft.com/library/wcedoc/vbce/sql.htm

 

CPCUG and TeraTech ColdFusion Conference
http://www.teratech.com/cfconf/

TeraTech maintains a ColdFusion code cuttings page called ColdCuts. The page also has links to about a dozen ColdFusion white papers in the CF Info Center.
http://www.teratech.com/ColdCuts/

The Maryland ColdFusion User Group meets the second Tuesday of each month at Westat, 1441 West Montogery, Rockville. Details and directions:
http://www.cfug-md.org/

The DC ColdFusion User Group meets the first Wednesday each month at Figleaf, 16th and P St NW, Washington DC. Details and directions:
http://www.figleaf.com/

Creating Dynamic Websites With ColdFusion
    — The CF Apprentice Series

Part 1: What is ColdFusion?
Part 2: Loops and Lists
Part 3: Dynamic E-Mail
Part 4: Verity Free Text Search
Published Sep. 17, 2003— Reads 10,881
Copyright © 2003 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
Related Links
▪ SourceCode
About Michael Smith
Michael Smith is president of TeraTech (www.teratech.com/), an
11-year-old Rockville, Maryland-based consulting company that
specializes in ColdFusion, database, and Visual Basic development.

Add Your Feedback

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers

ADS BY GOOGLE

Breaking Java News
Quaterra Converts Notes and Interest to Shares
GSI Group Calls Shareholders Meeting
Cannasat Therapeutics Reports Results for the Nine Months Ended September 30, 2009
Wal-Mart Court Ruling a Narrow Technical Victory
The Week Ahead for The Department of Justice for November 30 - December 4, 2009
Government of Canada, Government of Yukon and Communities Support Improvements to Recreational Facilities in Yukon
Norstar Securities Trust Announces Third Quarter Results
Canadian Pacific announces industry-leading biodiesel testing underway
Burnsville, MN Mayor Elizabeth Kautz Represents U.S. Mayors at EUROCITIES Meeting
LG Electronics Canada Welcomes Formula 1(TM) Back to Montreal

ADVERTISE   |   MAGAZINE SUBSCRIPTIONS   |   FREE BREAKING-NEWSLETTERS!   |   SYS-CON.TV   |   BLOG-N-PLAY!   |   WEBCAST   |   EDUCATION   |   RESEARCH

.NET Developer's Journal - .NETDJ   |   ColdFusion Developer's Journal - CFDJ   |   Eclipse Developer's Journal - EDJ   |   Enterprise Open Source Magazine - EOS
Open Web Developer's Journal - OPENWEB   |   iPhone Developer's Journal - iPHONE   |   Virtualization - Virtualization   |   Java Developer's Journal - JDJ   |   Linux.SYS-CON.com
PowerBuilder Developer's Journal - PBDJ   |   SEO / SEM Journal - SJ   |   SOAWorld Magazine - SOAWM   |   IT Solutions Guide - ITSG   |   Symbian Developer's Journal - SDJ
WebLogic Developer's Journal - WLDJ   |   WebSphere Journal - WJ   |   Wireless Business & Technology - WBT   |   XML-Journal - XMLJ   |   Internet Video - iTV
Flex Developer's Journal - Flex   |   AJAXWorld Magazine - AWM   |   Silverlight Developer's Journal - SLDJ   |   PHP.SYS-CON.com   |   Web 2.0 Journal - WEB2
Apache   |   CMS   |   CRM   |   HP   |   Oracle Journal   |   Perl   |   Python   |   Red Hat   |   Ruby on Rails   |   SAP   |   SaaS

SYS-CON MEDIA:   ABOUT US   |   CONTACT US   |   COMPANY NEWS   |   CAREERS   |   SITE MAP
SYS-CON EVENTS:   |  AJAXWorld Conference & Expo  |  iPhone Developer Summit  |  Cloud Computing Conference & Expo  |  SOA World Conference & Expo  |  Virtualization Conference & Expo
INTERNATIONAL SITES:   India  |  U.K.  |  Canada  |  Germany  |  France  |  Australia  |  Italy  |  Spain  |  Netherlands  |  Brazil  |  Belgium
 Terms of Use & Our Privacy Statement     About Newsfeeds / Video Feeds
Copyright ©1994-2008 SYS-CON Publications, Inc. All Rights Reserved. All marks are trademarks of SYS-CON Media.
Reproduction in whole or in part in any form or medium without express written permission of SYS-CON Publications, Inc. is prohibited.
 
close this window