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:
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:
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.
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="EmployeeList"
DATASOURCE="CompanyDB">
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.
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.
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
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.
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: