Getting Started Building ColdFusion MX Applications
Trademarks
1 Step RoboPDF, ActiveEdit, ActiveTest, Authorware, Blue Sky Software, Blue Sky, Breeze, Breezo, Captivate, Central,
ColdFusion, Contribute, Database Explorer, Director, Dreamweaver, Fireworks, Flash, FlashCast, FlashHelp, Flash Lite,
FlashPaper, Flex, Flex Builder, Fontographer, FreeHand, Generator, HomeSite, JRun, MacRecorder, Macromedia, MXML,
RoboEngine, RoboHelp, RoboInfo, RoboPDF, Roundtrip, Roundtrip HTML, Shockwave, SoundEdit, Studio MX, UltraDev,
and WebHelp are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or
in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within
this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in
certain jurisdictions including internationally.
This product includes code licensed from RSA Data Security.
Third-Party Information
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not
responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your
own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia
endorses or accepts any responsibility for the content on those third-party sites.
Getting Started Building ColdFusion MX Applications is intended for anyone who needs to begin
programming in the Macromedia ColdFusion MX 7 development environment. This manual
includes a tutorial, which uses supporting files that are installed if you chose to install sample
applications. If you did not install the ColdFusion MX sample applications, you can download
the tutorial files from the ColdFusion Support center on the Macromedia website.
About Macromedia ColdFusion MX 7 documentation
The ColdFusion MX 7 documentation is designed to provide support for the complete spectrum
of participants.
Documentation set
The ColdFusion MX 7 documentation set includes the following titles:
BookDescription
Installing and Using
ColdFusion MX
Configuring and
Administering
ColdFusion MX
ColdFusion MX
Developer’s Guide
Getting Started
Building
ColdFusion MX
Applications
Describes system installation and basic configuration for Microsoft
Windows, Solaris, and Linux. To see this manual, go to http://
www.macromedia.com/go/livedocs_cfmx7docs_installing.
Part I describes how to manage the ColdFusion environment, including
connecting to your data sources and configuring security for your
applications. Part II describes Verity search tools and utilities that you can
use for configuring the Verity K2 Server search engine, as well as creating,
managing, and troubleshooting Verity collections. To see this manual, go to
Describes how to develop your dynamic web applications, including
retrieving and updating your data, and using structures and forms. This
manual includes two volumes. To see this manual, go to
www.macromedia.com/go/livedocs_cfmx7docs_dev.
Contains an overview of ColdFusion features and application development
procedures. This manual includes a tutorial that guides you through the
process of developing a sample ColdFusion application. To see this manual
online, go to www.macromedia.com/go/livedocs_cfmx7docs_gs.
7
BookDescription
CFML Reference Provides descriptions, syntax, usage, and code examples for all ColdFusion
CFML Quick Reference Shows the syntax of ColdFusion tags, functions, and variables in a brief
tags, functions, and variables. This manual includes two volumes. To see
this manual, go to www.macromedia.com/go/
livedocs_cfmx7docs__cfml_reference.
guide.
Viewing online documentation
All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable
Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the
Macromedia website: www.macromedia.com. In addition, you can view the documentation in
LiveDocs, which lets you add comments to pages and view the latest comments added by
Macromedia, by going to www.macromedia.com/go/livedocs_cfmx7docs.
8Introduction:
PART I
Welcome to ColdFusion
Part I provides an introduction to Macromedia ColdFusion MX 7. It defines ColdFusion MX 7
and provides an overview of the ColdFusion Markup Language (CFML). It also provides generic
database concepts.
This chapter introduces the core technologies that are the foundation for Macromedia
ColdFusion MX. In addition, it introduces the basic concepts about ColdFusion MX, how it
works, and the various components that comprise it.
ColdFusion MX is a powerful web application server that lets you create robust sites and
applications without a long learning curve. ColdFusion MX does not require coding in traditional
programming languages (for example, C, C++, Java, XML), although it supports these traditional
programming languages.
ColdFusion MX consists of the following core components:
• ColdFusion application server
• ColdFusion Markup Language (CFML)
• ColdFusion MX Administrator
The following sections describe these core components in more detail. In addition, the Getting
Started Experience, which you can view by opening the Macromedia ColdFusion MX
Administrator and clicking Getting Started, provides introductory information about ColdFusion
and code snippets that highlight the new features of ColdFusion MX 7.
The ColdFusion application server
The ColdFusion application server is itself a web application that typically resides on the same
computer as your web server software. It is the program that parses (reads and interprets) and
processes supplied instructions. These instructions are passed to ColdFusion through ColdFusion
pages, which use a .cfm or .cfc filename extension. A ColdFusion page looks like an HTML page,
but contains special tags that instruct the ColdFusion server to perform specific operations.
11
The ColdFusion Markup Language
ColdFusion Markup Language (CFML) is a tag-based language similar to HTML that uses special
tags and functions. With CFML, you can enhance your standard HTML files with database
commands, conditional operators, and high-level formatting functions, and rapidly produce easyto-maintain web applications.
CFML looks similar to HTML: it includes start and end tags, and each tag is enclosed in angle
brackets. All ending tags are preceded with a forward slash (/) and all tag names are preceded
with cf.
The ColdFusion MX Administrator
You use the ColdFusion MX Administrator to configure and maintain the ColdFusion
application server. It is a web-based application that you can access using any web browser, from
any computer with an Internet connection.
You can manage the following configuration options with the ColdFusion MX Administrator:
• ColdFusion data sources
• Debugging output
• Server settings
• Application security
For further details about the ColdFusion MX Administrator, see Installing and Using ColdFusion MX or Configuring and Administering ColdFusion MX.
How ColdFusion processes pages
The following steps explain how the ColdFusion server processes a ColdFusion page:
1.
The ColdFusion server looks at the content of the page and searches for the following
ColdFusion instructions:
■ Tag names that begin with cf.
■ Variables and functions that are always surrounded by number signs (#).
2.
If the ColdFusion server finds any HTML or plain text in the page, the ColdFusion server
returns it to the web server unchanged.
3.
The ColdFusion server processes all the ColdFusion instructions found, and returns any
remaining results to the web server. The web server then sends the entire output to the browser.
12Chapter 1: Introducing ColdFusion MX
Building applications with CFML
You build ColdFusion applications as a series of pages that use CFML. Developers can extend this
language by creating their own custom tags or user-defined functions (UDF), or by integrating
COM, C++, and Java components, such as Java Server Page (JSP) tag libraries.
Interacting with data sources
ColdFusion applications can interact with any database that supports a JDBC technology-based
driver. A JDBC technology-based driver uses an Application Programming Interface (API) to
execute SQL statements to databases on most platforms. However, ColdFusion is not limited to
JDBC data sources. You can also interact with existing Open Database Connectivity (ODBC)
data sources by using ODBC Socket, a driver that interacts with an existing ODBC driver.
Interacting with mobile devices
ColdFusion MX 7 lets you create applications that can respond to events and messages from
diverse sources, including instant messaging, mobile phone Short Message Service (SMS) text
messages, Internet socket requests, and system events. For information, see Chapter 42, “Using
Event Gateways” in ColdFusion MX Developer’s Guide.
Development tools
You can code your ColdFusion application with NotePad or any HTML editor; however,
Macromedia recommends that you build your applications using Macromedia Dreamweaver MX.
Dreamweaver MX offers features and wizards that enhance ColdFusion development. For more
information about Dreamweaver MX, see Chapter 5, “Lesson 2: Configuring Your
Development Environment,” on page 49.
Building applications with CFML13
14Chapter 1: Introducing ColdFusion MX
CHAPTER 2
CFML Basics
This chapter introduces the basic elements of CFML, including how to create Macromedia
ColdFusion pages, and use variables, functions, conditional processing, and form processing.
ColdFusion pages are plain text files that you use to create web applications. You can create your
ColdFusion applications by writing all the code manually or by using wizards (provided with
some editors) to generate the majority of the code for you.
You can use the following editors to create your ColdFusion pages:
• Macromedia Dreamweaver MX
• Macromedia HomeSite+
• Macromedia ColdFusion Studio
• Any HTML editor
• Windows Notepad
• Vi or Emacs (UNIX systems)
15
The best choice for creating ColdFusion pages is Macromedia Dreamweaver MX. Dreamweaver
MX includes many CFML features for building applications, such as rapid visual development,
robust CFML editing, and integrated debugging. Dreamweaver MX also includes a copy of
HomeSite+ for users who are familiar with developing their application code using ColdFusion
Studio or HomeSite 5. HomeSite+ combines all the features of ColdFusion Studio and
HomeSite 5, along with support for the latest ColdFusion MX tags. For more information, see
Chapter 5, “Lesson 2: Configuring Your Development Environment,” on page 49.
Note: This manual describes how to create ColdFusion applications by writing your code manually. It
does not address how to create ColdFusion pages by generating code with wizards. For information
about using wizards to generate CFML code, see the product documentation for Dreamweaver MX
and HomeSite+.
Creating a ColdFusion page
Creating a ColdFusion page involves using tags and functions. The best way to understand this
process is to create a ColdFusion page.
In the following procedure, you will create a simple ColdFusion page by using HTML tags, one
ColdFusion tag, and two ColdFusion functions. The following table briefly explains the
ColdFusion tags and functions:
ElementDescription
Now()
DateFormat()
cfoutput
A function supported in CFML that you can use to retrieve information from your
system.
You will use the
that is retrieved from your system.
A function that instructs ColdFusion to format the date returned by the Now()
function.
A ColdFusion tag that you use to return dynamic data (data retrieved from a
database) to a web page.
You will use the
retrieved from your system.
Now() function in the following procedure to return the current date
cfoutput tag in the following procedure to display the current date
Note: ColdFusion tags and functions are considered primary elements of CFML. You will learn more
about these elements and others later in this manual.
To create a ColdFusion page:
1.
Open your editor and create a blank file.
2.
Enter the following code on the page:
<html>
<head>
<title>A ColdFusion Page</title>
</head>
<body>
<strong>Hello world, this is a ColdFusion page.</strong>
<br>
<cfoutput> Today’s date is #DateFormat(Now())# </cfoutput>
</body>
</html>
16Chapter 2: CFML Basics
Saving your ColdFusion page
In order for the ColdFusion server to process the page, you must save the ColdFusion page on a
computer where the ColdFusion MX is installed. If you are creating your pages on a local server
(on which ColdFusion is running), you can save the pages locally; if you are using a remote server,
you must save your pages on that server.
If you are using the ColdFusion MX J2EE configuration, you typically save ColdFusion pages
under the ColdFusion web application root. For example, in the default directory structure when
you use the J2EE configuration with JRun, you save pages under jrun_root/servers/cfusion/
cfusion-ear/cfusion-war. When you use JRun, you can also run the Web Server Configuration
Tool and save pages under your web root directory.
Tip: ColdFusion MX on Macintosh OS X uses the J2EE configuration.
To save the code that you typed to create a ColdFusion page:
1.
Create a directory called test under the web_root or web_application_root directory.
2.
In the test directory, save the file as cfpage.cfm.
Browsing your code
To ensure that the code you wrote is working as expected, you must view the ColdFusion page in
a browser. The following procedure describes how to view the ColdFusion page that you created
earlier.
To view the ColdFusion page:
1.
Open a web browser and go to the following URL:
http://localhost/test/cfpage.cfm
Note: If you are using the built-in web server, specify the port to use in the URL as follows:
http://localhost:8500/test/cfpage.cfm.
The address localhost is only valid when you view pages locally. The URL for a remote site
would include the server name or IP address of the server where ColdFusion is installed; for
example, http://<serveripaddress>/test/cfpage.cfm.
If you are using the ColdFusion MX J2EE configuration, you may also need to include a
context root in the URL; for example, http://<server>/<context-root>/<page>.cfm. For
example, if you deploy an EAR file and use the default context root of cfmx, you specify http:/
/localhost/cfmx/test/cfpage.cfm.
Working with ColdFusion pages17
The following figure shows the cfpage.cfm page in the browser:
2.
Do the following tasks:
a
View the source code that was returned to the browser. In most browsers, you can view the
source by right-clicking on the page, and then selecting View Source.
b
Compare the browser source code with the source code that appears in your editor. Notice
that the CFML tags were processed on the page but did not appear in the source that was
returned to your browser.
As described in Chapter 1, “Introducing ColdFusion MX,” on page 11, ColdFusion
processes all the instructions (CFML tags and functions) it receives on a page, and then
returns the results of the instructions that your browser can interpret and display.
About CFML elements
CFML consists of two primary language elements: tags and functions. Ta g s let you perform
operations such as accessing a database. Functions can return data and do other operations like
retrieving the system date. Almost everything that you want to accomplish with ColdFusion
involves using tags and functions.
You use another important element known as a variable. Variables are an important part of most
programming languages and are equally important with CFML. Var ia bl es let you store
information in memory and enable you to pass data.
The following sections describe how to use these three elements.
Tags
You can think of tags as commands that you use to instruct the ColdFusion server to perform
operations. These operations might include selecting data from a database, reading a file that
resides on the server, or showing the results of processing.
Tag syntax
As discussed in Chapter 1, “Introducing ColdFusion MX,” on page 11, ColdFusion tags are
similar to HTML tags. ColdFusion tags are enclosed in angle brackets and often have a start and
end tag. The start tag encloses the tag name in brackets, like this:
<tagname>
18Chapter 2: CFML Basics
Most often the end tag encloses the tag name in brackets and includes a forward slash (/),
like this:
</tagname>
The information processed by ColdFusion is placed between the start and end tag, like this:
<tagname>
info to be processed ...
</tagname>
ColdFusion tags, for the most part, share these common characteristics:
• All start with cf.
• Include a start and end tag.
• Use attributes (like HTML tags), and most attributes have values.
Some ColdFusion tags, such as
cfset, omit the ending tag. This type of tag uses one set of angle
brackets and places all the required information between the left (<) and right (>) angle brackets,
like this:
<cfset name="bob">
For a complete list of tags and their syntax, see CFML Reference.
Tag attributes
Tag attributes instruct ColdFusion about the details of an operation. For example, to update a
database table, ColdFusion requires specific information about the database, such as the database
name and the table name. The code required to write this type of statement might look like this:
<cfupdate datasource="mydb" tablename="mytable">
where datasource and tablename are attributes of the cfupdate tag and "mydb" and
"mytable" are attribute values.
For a complete list of tags and their attributes, see CFML Reference.
Functions
Typically, a function acts on data. It can generate a value or a set of values, usually from some
input. You can perform the following operations (actions) with functions:
• Manipulate data and time values
• Examine a value or variable
• Display and format information
• Manipulate string data
• Retrieve system information and resources
• Perform mathematical operations
About CFML elements19
Functions and number signs
You use number signs (#) with functions to display the results of a function on the page. Number
signs tell the ColdFusion server to evaluate the content between the number signs and display the
value, for example:
<cfoutput>
Hello world, <br>
Today’s date is #DateFormat(Now(), "mm/dd/yyyy")#
</cfoutput>
The following figure shows the output of this example:
If you did not include the number signs around the
DateFormat(Now(), "mm/dd/yyyy")
function, ColdFusion would not evaluate the function and the previous example would display
your source code, as follows:
For more information about how to use number signs with functions, see ColdFusion MX Developer’s Guide.
Functions and parentheses
All functions have parentheses, regardless of whether the function acts on data. Consider the
following function:
#Now()#
If you put anything inside the parentheses of the Now() function, an error would occur. The
Now() function returns an unformatted date and time. However, you can format the results of
this function with other functions, such as the
DateFormat() or TimeFormat() functions.
20Chapter 2: CFML Basics
Using functions on values
Usually, a function performs an operation on a value, and the value can include the value of a
variable. For example, to format the value of a variable that contains a value in dollars, the code to
write this statement might look like this:
#DollarFormat(price)#
The DollarFormat function returns a value as a string and formats that value with two decimal
places, a thousands separator, and a dollar sign. The number signs (#) around the function
instruct ColdFusion to evaluate the content between the number signs and display the value.
Nesting functions
Functions can generate data, as well as act on data. Consider the following example:
#DateFormat(Now(), "mm/dd/yyyy")#
In this example, the Now() function generates the date, and then the DateFormat function
formats the date.
Variables
Variables let you store data in memory on the server. Variables always have a name and a value.
You can assign a value to a variable, or you can instruct ColdFusion to assign variable values based
on data that it retrieves from a data source, such as a database table.
Naming variables
You must use the following rules for naming ColdFusion variables:
• Names are case-insensitive (uppercase, lowercase, or mixed case).
• Names can contain only letters, numbers, and underscore characters.
• Each name must begin with a letter.
• Special characters (such as double-quotation marks ("), reserved names (such as functions and
tags), and spaces are not allowed.
Ways to use variables
You can use variables for the following purposes:
• Store data collected from a form.
• Store results of a calculation (such as the number of database records returned).
• Use as input to a function.
Creating variables with the cfset tag
ColdFusion lets you create variables as you need them. You create the variable (name and value)
using the
<cfset variable_name = value>
cfset tag. This tag has the following syntax:
About CFML elements21
In the following examples, the variables are assigned a string literal value. All string literal values
are surrounded by double-quotation marks.
Tip: String values assigned to a variable must be enclosed in single-quotation marks (') or doublequotation marks ("). Numeric or Boolean values assigned to a variable do not require single- or
double-quotation marks.
So far, all the variable examples have shown local variables. Local variables are variables that you
can use only on the current ColdFusion page. The previous example used a variables prefix to
reference an existing variable on the page. Using a prefix when referencing a variable is important
because ColdFusion supports many types of variables. Use the following syntax to reference a
local variable:
variables.variablename
Because ColdFusion lets you use the same name with variables of more than one type,
ColdFusion relies on scope referencing. In scope referencing, you preface the variable’s name with
the scope when you refer to that variable.
Other variables and their scope
Each type of variable that ColdFusion supports has it own scope, or where it can be referenced,
and its own way of referencing that variable type. The following table identifies some of the more
common types of variables and their prefixes:
ScopePrefixDescription
Variables
(local variable)
FormFormData entered in tags in an HTML form or ColdFusion form and
URLURLVariables passed to a page as URL string parameters.
QueryQueryName Variables that have names based on the column names that you select
VariablesVariables created using a
the variable on the current page or on a page that you include using
the
cfinclude tag.
processed on the action page.
in the database table. The values are created when you execute the
query that selects data from the database.
cfset or cfparam tag. Most often you define
You will use these other types of variables in Part II of this manual. For additional information
about variables, see CFML Reference.
22Chapter 2: CFML Basics
Displaying variable output
Output is what remains after the ColdFusion server processes the CFML tags on a page. Usually
the output has two parts:
• Information that the user sees (for example, a confirmation message)
• Information that is stored by the server as a result of processing (for example, user input
collected from a form)
One of the tags that ColdFusion provides to display output is the
tag instructs ColdFusion to process all the code between the
syntax for the
<cfoutput>
{normal html, text, and ColdFusion processing instructions}
</cfoutput>
cfoutput tag looks like this:
To return the value of a variable, you must always surround the variable name with number signs
(#) and place the variable name between the
cfoutput start and end tags. For example, the
following code creates a variable and instructs the ColdFusion server to return the value of the
variable:
Expressions are an important part of the ColdFusion language. Expressions are a collection of
different elements, ColdFusion variables, functions, and operators. You can think of them as
strings of text that consist of one or more of the following elements:
• Literal text (string), numbers, dates, and other values
• Variables
• Functions
• Operators (& for joining statements, + for addition, and so on)
This chapter includes many examples of expressions; for example:
• #variables.my_full_name#
• DateFormat(Now())
• my_first_name= "Kaleigh"
When you build expressions in ColdFusion, you can include simple and complex elements; how
you represent these elements determines how ColdFusion processes your application.
Working with CFML expressions23
Building expressions
In ColdFusion, you build expressions as you need them. The expressions can include simple
elements, such as the expressions shown previously, or they can include complex elements, such as
arithmetic functions, strings, and decision operators. (You build some complex expressions in Part
II of this manual.)
As mentioned, it is important that elements are identified properly in your expression so that
ColdFusion processes them as expected, and you avoid unnecessary errors. When you write
expressions, consider the following coding practices:
• Use of consistent character case
• When to use number signs (#)
• When quotation marks are needed
Specifying a consistent character case
Because the ColdFusion server is case-insensitive, you can write expressions using all uppercase,
all lowercase, or mixed case. However, for code readability and consistency, you should use the
same character case in all your programs. If you write your programs using the same case rules,
you might prevent errors from occurring when you combine CFML on a page with case-sensitive
languages, such as JavaScript.
Specifying number signs to denote functions or variables
In ColdFusion, you specify number signs (#) to denote functions and variables within a string of
text. You use number signs to show the results of the function or variable on the page. Number
signs instruct the ColdFusion server to evaluate the function (or variable) between the number
signs and display the value. The value of the function (or variable) appears in the browser as a
result.
The following are some common ways to use number signs:
• In the following example, you include the number signs to return the value to a page:
• To display a number sign on a page, you must designate the number sign as a literal character.
You do this by using two number signs (##); for example:
<cfoutput>
##1: Your name.
</cfoutput>
The result is the following output:
#1. Your name.
24Chapter 2: CFML Basics
For more information and examples on using number signs in expressions, see ColdFusion MX
Developer’s Guide.
Specifying quotation marks around values
When you assign literal values to variables, you must surround the literal value with single- or
double-quotation marks. ColdFusion interprets the content between the quotation marks as a
literal value and assigns that value to the variable; for example:
ColdFusion instantiates the variable my_first_name to the string literal Kaleigh. Further, Smith
is assigned to the variable
my_last_name and 5 is assigned to age.
When referencing a variable by its name, you do not surround the name with quotation marks. In
the following example, when you concatenate literal text and variables using the & operator, you
don’t surround the variable references with quotation marks:
<cfset the_string = "My name is " & variables.my_first_name &
" and my age is " & variables.my_age>
My name is
references
marks. ColdFusion uses the values of the referenced variables (
assigning the value to the variable
is literal text, and you, therefore, surround it with quotation marks. The variable
variables.my_first_name and variables.my_age are not surrounded by quotation
Kaleigh and 5, respectively) when
the_string.
To display quotation marks on a page as literal characters, you must use two consecutive
quotation marks; for example:
<cfset mystring = "We all shouted ""Happy Birthday"" when he entered the
room.">
<cfoutput>
#mystring#
</cfoutput>
The result is the following output:
We all shouted "Happy Birthday" when he entered the room.
Specifying operators in expressions
In ColdFusion, you use operators to test conditions; for example, you use the
IS operator to test
for equality. When you use operators in expressions, you must only use supported logical
operators that ColdFusion can interpret properly. For example, if you use the greater than
operator (>) or the less than operator (<), ColdFusion interprets them as the start or end of a tag
rather than as an operator.
Working with CFML expressions25
The following table lists the unsupported logical operators and their equivalent ColdFusion
operators:
Unsupported
logical operator
=IS, EQUAL, EQTests for equality.
<LT, LESS THANTests for less than.
<=LTE, LE,
>GT
>=GTE,
< >IS NOT, NEQ,
CONTAINSTests whether a value is contained within a
DOES NOT CONTAINTests whether a value is not contained
Equivalent ColdFusion
decision operator
LESS THAN OR EQUAL TO
GREATER THAN
GREATER THAN OR EQUAL TO
NOT EQUAL
Description
Tests for less than or equal to.
Tests for greater than.
Tests for greater than or equal to.
Tests for nonequality.
second value.
within a second value.
Arithmetic operators
The following table lists the arithmetic operators that ColdFusion supports:
Operators Description
+, -, *, / The basic arithmetic operators: addition, subtraction, multiplication, and division.
+, - Unary arithmetic operators for setting the sign of a number as either positive or
ModReturns the remainder (modulus) after a number is divided by a divisor. The result
\ Divides two integer values. Use the \ (backslash character) to separate the
^ Returns the result of a number raised to a power (exponent). Use the ^ (caret) to
In the case of division, the right operand cannot be zero.
negative (+ or -).
has the same sign as the divisor. The right operand cannot be zero. For example,
11 MOD 4 is 3.
integers. The right operand cannot be zero. For example, 9 \ 4 is 2.
separate the number from the power. The left operand cannot be zero. For
example, 2 ^ 3 is 8.
26Chapter 2: CFML Basics
String operator
The following table describes the one ColdFusion string operator that is a concatenation
operator:
OperatorDescription
&Concatenates strings.
About conditional processing
So far, all the coding examples shown in this chapter are considered linear coding examples.
Linear code is when ColdFusion executes code starting with the first line on the page, and
processes every line in order. Although you will use linear code in your applications, you will
often write code that performs various actions based on conditions, such as the following:
• Determine whether a user entered a value in a form field.
• Display results based on user input.
• Display messages based on the time of day.
You use conditional processing to customize the behavior of your application. Conditional processing facilitates decision making and lets you control how the code on a page is processed.
In ColdFusion, you implement conditional processing with flow control tags. These tags are
similar to other programming language control elements, such as
using these tags, you can facilitate decision making in your code. The most fundamental tags used
to control code execution are the
cfif, cfelse, and cfelseif tags. Because you will see and use
these tags in Part II of this manual, the following sections provide a basic introduction on how to
use these tags. For more information about other conditional processing tags, including tags for
looping, see ColdFusion MX Developer’s Guide.
if, then, and else. When
Using the cfif tag to evaluate True or False conditions
To create statements that let you evaluate conditions and perform an action based on the result,
you use the
<cfif expression>
HTML and CFML tags executed if expression is True.
</cfif>
cfif tag to create a cfif statement. The basic syntax is as follows:
In this example, ColdFusion only executes the code inside the cfif statement if the expression
evaluates to True. To perform actions if the expression is False, you can use the
example, if the following
the ending
<cfif expression>
HTML and CFML tags executed if expression is True.
<cfelse>
HTML and CFML tags executed if expression is False.
</cfif>
cfif tag is processed:
cfif expression evaluates to False, the code between the cfelse tag and
About conditional processing27
cfelse tag. For
Using the cfelseif tag to evaluate multiple expressions
To evaluate multiple expressions in a
cfif statement, you can use cfelseif and cfelse tags in
your statement; for example:
<cfif expression 1>
HTML and CFML tags executed if expression 1 is True.
<cfelseif expression 2>
HTML and CFML tags executed if expression 2 is True.
<cfelse>
HTML and CFML tags executed for expression(s) that is False.
</cfif>
The following example shows you how you can evaluate multiple expressions using these tags.
This example uses a form in which users can enter their state to determine their state tax:
<cfoutput>
<cfif form.state IS "MA">
#form.state# State Tax: 8.5%
<cfelseif form.state IS "VA">
#form.state# State Tax: 8.2%
<cfelse>
#form.state# State Tax Unknown
</cfif>
</cfoutput>
The output of this cfif statement is based on the value entered by the user. If the user enters MA
in the state form field, the state tax results returned is 8.5%. If the user enters VA in the state form
field, the state tax results returned is 8.2%. If the user enters any other state in the state form field,
State Tax Unknown is returned.
Processing form data
Virtually all web applications that gather and write information to a database use a form to
accomplish that task. Forms let you collect information from a user (using an order form,
registration form, and so on) and write that information to a database. Like HTML, there are two
independent steps for creating a form in ColdFusion:
1.
Creating the layout for the form itself.
2.
Writing the code to process the submitted information.
Every form that you create in ColdFusion consist of two parts: the form page and the action page.
These two pages work together to process user input. The form page contains the user interface
elements, such as input fields and radio buttons. The action page handles the processing of the
form page data.
28Chapter 2: CFML Basics
When a user submits a form, the form values are stored in form variables and sent to the action
page for processing. The following figure shows the relationship between the form page and
action page:
Form page
Name
E-mail
Submit
The action page contains
the code for form processing
and interaction with
database.
form.var1=value1
form.var2=value2
ColdFusion server &
web server
Action
page
Database
In order for the form page to find its corresponding action page, the action statement in the form
tag must be correct. The form tag includes the information that tells the server where to send the
data that it collects. It also tells the server how to send it. To process these instructions to the
server, the form tag uses the following syntax:
<form action="actionpagename.cfm" method="Post">
HTML and CFML form tags
</form>
The first attribute (action) in the form tag lets you specify where to send the data. The page that
you specify where to send the data is the name of the action page. The second attribute in the
form tag is
must set the method attribute to
method. The only method that ColdFusion supports is post. All ColdFusion forms
post.
In Part II of this manual, you use ColdFusion form tags to create forms and write collected values
to a database.
Processing form data29
Commenting your code
As in other programming languages, it is important to include comments in your code. You
should comment your code for the following reasons:
• Commented code is easier to debug than code that is not commented.
• If you describe the code on the page, it is easier to make modifications.
• Commented code tends to be better organized.
Comment tag
The ColdFusion comment tag is similar to the HTML comment tag, except that it has three
dashes instead of two:
<!--- This is a CFML comment --->
ColdFuions comments can wrap to more than one line. ColdFusion comments are not returned
to the browser because the ColdFusion server processes and omits the comments from the page.
The user will never be able to read your comments.
30Chapter 2: CFML Basics
CHAPTER 3
Database Fundamentals
This chapter provides a quick overview of relational database concepts and terms. It describes
what a database is and how it is organized. It also discusses the Structured Query Language (SQL)
that you use to interact with databases.
Even though you do not need a thorough understanding of database management systems to
create ColdFusion applications, you must understand some basic concepts and techniques about
databases. The information in this chapter will help you get started using ColdFusion.
31
What is a relational database?
A relational database is a structured collection of information that is related to a particular subject
or purpose, such as an inventory database or a human resources database. You use databases to
manage information. Information, such as product name, cost, and on-hand inventory, is stored
in a database. Within the database, you organize the data into storage containers called tables.
Ta b l e s are made up of columns and rows. Columns represent individual fields in a table. Rows
represent records of data in a table. You can think of database tables as grids, as in the following
example:
Field (column)
Record
(row)
Each field in the table contains one piece of information. In an employee table, for example, one
column contains the employee name, another contains the employee phone number, and the
other columns each store one piece of information, such as the address, city, state, zip, and salary
information. Each record represents one set of related information. For example, an employee
table might store information about one employee per row. The number of rows in a table
represents the total number of table records.
32Chapter 3: Database Fundamentals
About relational tables
In a database, you can organize data in multiple tables. For example, if you manage a database for
the Human Resources department, you might have one table that lists all the information about
employees and another table that lists all the departments:
You have multiple departments for employees, but you would not store the information about the
departments in every employee row for the following reasons:
• The department information is the same for each employee in a given department; however,
repeating the department information for each employee is redundant. Storing redundant data
takes up more disk space.
• If the department information changes, you can update one occurrence. All references to that
department are updated automatically.
Storing multiple occurrences of the same data is rarely a good thing. Good relational database
design separates application entities into their own tables. Key values from one table are often
stored in a related table rather than repeating the information. The key value is used to join the
data between the tables to return the complete set of data required.
About database basics33
About SQL
SQL (Structured Query Language) is a language that lets you communicate with databases. For
example, you can use SQL to retrieve data from a database, add data to a database, delete or
update records in a database, change columns in multiple rows, add columns to tables, and add
and delete tables.
Unlike other computer languages, SQL is made up of a small number of language elements that
let you interact efficiently with a database. Some of the more frequently used elements include the
following SQL commands:
CommandUse
SELECTRetrieve (query) information in a database.
INSERTAdd records to a database.
UPDATEUpdate information in a database.
DELETEDelete information in a database.
Understanding basic SQL SELECT statements
One of the most widely used SQL statements is the SELECT statement. The SQL SELECT
statement retrieves columns of data from a database. The tabular result is stored in a result table
(called the record set).
You use the following SELECT statement to retrieve information from a table:
SELECT column_name(s) FROM table_name
Consider a table named Clients that contains the following rows:
LastNameFirstNameAddressCity
BrownMarie12 State StBoston
AdamsRussell521 Beacon StBoston
CarterJoan1 BroadwayNew York
To select the columns named LastName and FirstName, use the following SELECT statement:
SELECT LastName, FirstName FROM Clients
The result of this SQL statement contains the following data:
LastNameFirstName
BrownMarie
AdamsRussell
CarterJoan
34Chapter 3: Database Fundamentals
Using the SQL WHERE clause to limit the rows returned
To conditionally select data from a table, you can add a WHERE clause to the SELECT
statement, which results in the following syntax:
SELECT column_name FROM table_name WHERE column condition value
With the WHERE clause, you can use any of the following operators:
OperatorDescription
=Equal
<>Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
BETWEENBetween an inclusive range
ANDJoins one or more conditions
ORJoins one or more conditions
LIKESpecifies a search for a pattern in a column. You can use a percent sign
(%) to define wildcards (missing letters in the pattern) before and after the
pattern.
For example, to select the columns named LastName and FirstName for Clients whose City is
Boston, use the following SELECT statement:
SELECT LastName, FirstName FROM Clients Where City = 'Boston'
The result of the preceding SQL statement contains the following data:
LastNameFirstName
BrownMarie
AdamsRussell
You can compose a WHERE clause with one or more conditions; these are called subclauses. You
join subclauses using the operators AND and OR. The AND operator displays a row if all
conditions that are listed are True. The OR operator displays a row if any of the conditions listed
are True. The following statement shows an example of a WHERE clause with multiple
subclauses:
SELECT LastName, FirstName FROM Clients Where City = 'Boston' AND FirstName =
'Marie'
About SQL35
The result of the preceding SQL statement contains the following data:
LastNameFirstName
BrownMarie
Note: The preceding SQL SELECT examples use single-quotation marks around the value. SQL
uses single-quotation marks around text values. Most database systems also accept doublequotation marks. Do not enclose numeric values in quotation marks.
Sorting the results
You use the ORDER BY clause to sort the result rows. The following SQL statement returns an
alphabetic list of people sorted by last name, and then first name, from the Clients table:
SELECT * FROM Clients Order By LastName, FirstName
The default is to return the results in ascending order (top to bottom). If you include the DESC
keyword in the ORDER BY clause, the rows are returned in descending order (bottom to top).
The following statement returns a reverse alphabetic list of the Clients table:
SELECT * FROM Clients Order By LastName, FirstName DESC
Note: The SQL SELECT statement is quite powerful. There are several other options for retrieving
data from a SQL database using the SELECT statement, which are not described in this manual. For
more information, consult a SQL reference.
Using SQL with ColdFusion
ColdFusion communicates with your data source through a database interface called Java
Database Connectivity (JDBC). JDBC is a standard application programming interface (API) for
accessing information from different database systems and different storage formats.
About data sources
A data source is a complete database configuration that uses a JDBC driver to communicate with
a specific database. In ColdFusion, you must configure a data source for each database file that
you want to use. After you configure a data source, the ColdFusion server is then capable of
communicating with that data source through the JDBC driver.
You configure data sources in ColdFusion by using the ColdFusion MX Administrator. For
information about how to configure the sample data source file that is supplied for use with Part
II of this manual, see “Lesson 2: Configuring Your Development Environment” on page 49. For
more information about configuring a data source in ColdFusion, see Installing and Using ColdFusion MX or ColdFusion MX Developer’s Guide.
36Chapter 3: Database Fundamentals
Writing SQL and CFML statements to interact with a data source
After ColdFusion makes a connection to the data source, you can interact with that database by
using SQL and ColdFusion.
To interact with an established data source, you must include SQL statements in your CFML
statements; for example:
In this example, the first attribute of the cfquery tag is the name of the query. The second
attribute of the
cfquery tag defines the name of the data source. The SELECT statement defines
the fields (columns) to be retrieved from a table named Employee.
CFML tags that interact with a database
The following table lists the CFML tags that you can use to interact with a database:
TagDescription
cfquery
cfinsert
cfupdate
To retrieve (query) information in a database.
To add records to a database.
To update information in a database.
Part II of this manual introduces these tags when you use them to interact with the sample
database. For more information about interacting with a database, see ColdFusion MX Developer’s Guide or CFML Reference.
Using SQL with ColdFusion37
38Chapter 3: Database Fundamentals
PART II
Building a ColdFusion Application
Part II provides a tutorial that steps you through building a sample Macromedia ColdFusion
application. It consists of the following lessons:
This tutorial guides you through the process of building a simple Macromedia ColdFusion web
application. By the end of the tutorial, you will be familiar with how to use Macromedia
ColdFusion MX 7 to query and update a database, validate data, generate a report, and require
user authentication.
The application that you will build in this tutorial is for a fictitious travel company called
Compass Travel. Compass Travel markets a wide range of adventure trips to the public through its
website. Trip coordinators at Compass Travel are responsible for maintaining the trip
information. The sample tutorial application assists the trip coordinators in maintaining trip
information in the Compass Travel database.
ColdFusion development is the emphasis of the tutorial; therefore, you will not need to design or
build the Compass Travel database. It is important, however, for you to be familiar with the
layout of the database. Additionally, you must understand the functional requirements that will
help determine the application design. This lesson provides an overview of these application
design steps, while the remainder of this manual guides you through the lessons on constructing
the sample application.
Application development steps
Most software applications contain three major functions:
• A user interface to capture data
• Logic to validate the captured data
• A database to store the validated data
The steps to develop these major functions vary from project to project. In this tutorial, you will
review or participate in the following application development steps to build the Compass Travel
Trip Maintenance application:
StepDescription
1Determine the application functional requirements.
2Determine the data requirements by identifying the information required for the Trip
Maintenance application.
41
StepDescription
3Design the database for your application by exploring the database tables that will store
4Develop the ColdFusion application pages.
the trip information.
The following sections explore an overview of each of these application development steps.
Exercise 1: Determining the application functional requirements
Before you can build the sample application, you must understand the functional requirements
that influence its design. The design of the sample application centers around the daily tasks
performed by Compass Travel’s trip coordinators. The following table describes these tasks:
Trip coordinator taskDescription
Produce current trip
listing
Provide trip information On an ad hoc basis, Compass Travel management asks the trip
Maintain trip information The trip coordinator is responsible for keeping all trip information up to
Ensure the quality of trip
information
To help Compass Travel agents take trip reservations on the telephone
and in person, the trip coordinator maintains a list of current trip offerings.
coordinator to develop lists of trips that meet specific criteria.
date. To do this, the coordinator needs to locate a trip to edit it or delete it.
Additionally, the coordinator must be able to add a new trip.
The trip coordinator is responsible for periodically browsing the current trip
offerings to ensure that all the information is accurate. Additionally, when
adding a new trip or editing an existing one, the trip coordinator must
ensure that the data adheres to the Compass Travel business rules.
You can derive several functional requirements for the new application from the preceding table.
For example, the sample application must provide the ability to do the following:
• Generate trip listings.
• Find trips based on user-supplied criteria.
• Browse trips.
• Add a new trip.
• Delete an existing trip.
• Edit an existing trip.
• Validate new or updated trips against Compass business rules.
In the lessons that follow, you will build ColdFusion pages to address each of these functional
requirements. The basis for every requirement is the idea of a trip. Before you can build code to
address any of these requirements, you must understand which attributes of a trip are important
to Compass Travel. For this you must determine the data requirements for the application.
Understanding the data requirements is essential to building the proper database to hold the
application data.
42Chapter 4: Lesson 1: Preparing to Build the Sample Application
Exercise 2: Determining the data requirements
Prior to creating the application pages to capture trip information, you must determine what type
of data is required about each trip. For the example in this tutorial, the Compass Travel trip
coordinator must maintain the following information about each trip:
• Tr i p n am e
• Type of event (surfing, mountain climbing, kayaking, and so on)
• Trip description
• Trip location
• Departure date
• Return date
• Price
• Base cost
• Assigned trip leader
• Total number of people who can attend the trip
• An indicator of whether a deposit is required
• Trip photograph
By collecting the preceding information about each trip, the Compass Travel website can market
its trips online to the general public. Customers who are booking a trip need to know the trip
name, when the trip begins and ends, the price, and a description. Additionally, the trip
coordinator must identify the filename for a photograph of each trip. The Compass Travel
website displays the photograph to further entice prospective customers into booking the trip.
Finally, Compass Travel considers it important to store the base cost for each trip to help
determine trip profitability. The cost must be captured, but it is for Compass Travel internal use
only and is not shown on the public website.
Exercise 3: Designing the database for your application
After you identify the information to collect, you must consider where to store the data. Prior to
creating the data collection form and instructing ColdFusion where to store the form data, you
must have a database ready to accept the data.
Exercise 3: Designing the database for your application43
If you had to create the Compass Travel database, you would create a table named trips to store
the information that you plan to collect about each trip. The table would look something like the
following table:
Recognizing the data types
Each field in the Trips table has a data type attribute that describes the type of data that can be
stored in the column. For instance, the tripName column can contain text data, while the price
column can only contain numeric data. It is important to know what type of data is valid for
each column so that your data collection forms can validateagainst incorrect values entered by
the user.
Looking closer, you might wonder why the eventType column is a number and not a text data
type column. Recall that data requirements analysis identified the need for a type of event
(surfing, mountain climbing, kayaking, and so on). The purpose of this column is to classify trips
into various categories based on the trip activity. It is essential that the application classify the trips
consistently. Therefore, it is important to offer a list of event types for the user to select, rather
than to accept free text input.
To present a list of event types for user selection, the event types are stored in a separate table, the
eventtypes table. This table is already populated and contains the following rows:
44Chapter 4: Lesson 1: Preparing to Build the Sample Application
Establishing a relationship between the two tables
When the user selects an event type from the list obtained from reading the eventtypes table, the
correct event type must be saved to the trips table with all the other trip-related data. The
application could store the eventType (for example, mountain climbing) itself into the eventType
column in the trips table. But if the name Mountain Climbing were later shortened to Climbing
in the eventtypes table, new mountain climbing trips would be classified differently than ones
saved before the change. For this reason and to save space in the database, the key to the
eventtypes row (eventTypeID) is stored in the trips table instead.
The two tables are said to have a relationship. This relationship works by matching data in key
fields. In this case, the matching fields consist of a primary key (eventTypeID) from the eventtypes
table, which provides a unique identifier for each record, and a foreign key (eventType) in the trips
table. The foreign key contains the same value as the primary key, pointing to a unique event
type. The following figure shows this relationship:
Exercise 3: Designing the database for your application45
Exercise 4: Developing the sample application
Using the application functional requirements and the database that is provided for this tutorial,
you are ready to use ColdFusion to develop the Trip Maintenance application. The remaining
lessons in the tutorial step you through the process of constructing this application. When you are
done, the main page for the Trip Maintenance application will appear as follows:
The main application page is where users will come to view information about trips and to
navigate to other ColdFusion pages to add, edit, or search for new trips.
The following lessons explain how to do these tasks:
• Configure your development environment (“Lesson 2: Configuring Your
Development Environment” on page 49).
• Retrieve data from a database (“Lesson 3: Retrieving Data” on page 59).
• Build dynamic queries (“Lesson 4: Building Dynamic Queries” on page 71).
• Build the trip detail page (“Lesson 5: Creating a Trip Detail Page” on page 85).
• Build the main application page (“Lesson 6: Creating a Main Application Page” on page 97).
• Write code to enforce Compass Travel business rules (“Lesson 7: Validating Data to Enforce
Business Rules” on page 103).
46Chapter 4: Lesson 1: Preparing to Build the Sample Application
• Implement browsing and searching (“Lesson 8: Implementing Browsing and Searching”
• Restrict access to the Compass Travel application by requiring user authentication (“Lesson 10:
Restricting Access to ColdFusion Applications” on page 143).
How to proceed
Each lesson in the tutorial is designed to let you proceed at your own pace. At any time, you can
stop and later return to that place in a lesson so that you can complete all the sections in the
lesson.
Each lesson guides you through a scenario to enhance the Compass Travel Trip Maintenance
application. Sections within a lesson present basic programming concepts that you need to
understand before completing the section exercises.
Depending on your programming experience, you can read the entire lesson and then proceed to
the hands-on exercises, or you can skip some information in the lesson and proceed directly to the
exercises. For each exercise, there is a completed version of each file created or modified in that
lesson. The completed solution files are in the directory cf_root/cfdocs/getting_started/solutions.
Appended to each filename is the lesson and exercise number. For example, the version of the file
tripdetail.cfm that you would have after performing the steps in Lesson 5, Exercise 4 is named
tripdetail_lesson5_ex4.cfm. To use the solution file and continue with Lesson 5, Exercise 5, copy
the tripdetail_lesson5_ex4.cfm file to the cf_root/cfdocs/my_app directory, and overwrite the
tripdetail.cfm file if it already exists in the my_app directory.
Working directories
The following table describes the working directories for this tutorial:
DirectoryDescription
my_appYou save all your source code in this directory.
solutionsYou can find solutions to all the exercises in this directory.
dbYou use this directory as the working directory for the Compass Travel database.
photosYou use this directory to access existing trip photographs.
imagesYou use this directory to access application image files.
Locating the working directories
The working directories for this tutorial are under your web root directory. For example, the
directory path on your computer might look like the following:
• (On Windows) web_root\cfdocs\getting_started
• (On UNIX) web_root/cfdocs/getting_started
Note: When using the J2EE configuration, the cfdocs directory is under the ColdFusion web
application root. For more information, see “Saving your ColdFusion page” on page 17.
Exercise 4: Developing the sample application47
You can view ColdFusion application pages on your local computer by opening a web browser
and entering one of the following URLs:
For more information about the tutorial file structure and the location of the getting_started
subdirectories, see “Exercise 1: Verifying the tutorial file structure” on page 49.
Requirements
To use this tutorial, you must have the following components installed:
ColdFusion MX 7 For information on how to install ColdFusion MX 7, see Installing and Using ColdFusion MX.
Database Management System A database management system can be installed on the same
computer as ColdFusion MX or on a separate computer. For the purpose of this tutorial, a
Microsoft Access database file for Microsoft Windows users and a PointBase database file for
UNIX users have been provided. For information about how to configure the Compass Travel
data source, see “Lesson 2: Configuring Your Development Environment” on page 49. For
additional information about configuring a data source, see Installing and Using ColdFusion MX.
Web browser You can use Microsoft Internet Explorer (4.0 or later) or Netscape Navigator
(6.0 or later).
Text editor or IDE (Interactive Development Environment) In order to use the Macromedia
Dreamweaver Extensions described in this tutorial, you must use Dreamweaver MX 2004.
However, you can use Macromedia HomeSite+, ColdFusion Studio, any text editor, or IDE, and
copy and paste the code that the Dreamweaver Extensions create. In the exercises in this tutorial,
the term editor means Dreamweaver MX 2004, HomeSite+, ColdFusion Studio, or any text
editor or IDE of your choice.
48Chapter 4: Lesson 1: Preparing to Build the Sample Application
CHAPTER 5
Lesson 2: Configuring Your
Development Environment
In this lesson, you set up your development environment for the tutorial. This lesson describes
the tutorial file structure, and how to configure the database connection and debugging options.
Additionally, it provides an overview of using Macromedia Dreamweaver MX for Macromedia
ColdFusion development.
This lesson explains how to do the following tasks:
Before you begin the tutorial, verify that the configuration of the computer where
ColdFusion MX 7 is installed matches the file structure described in the following sections.
The files required to complete the Compass Travel tutorial are installed under the web server root
directory. The location of this directory varies, depending on whether you chose to configure a
local third-party web server (such as IIS) or the ColdFusion stand-alone web server during
installation, as follows:
• When you use a third-party web server (such as IIS or Apache), the files are installed in:
web_root/cfdocs/getting_started.
• When you use the ColdFusion built-in web server, the files are installed in:
cf_root\webroot\cfdocs\getting_started.
The following is the getting_started directory structure:
getting_started
-db
-my_app
-images
-new_user_database
-photos
-solutions
49
Note: When you use the J2EE configuration, the cfdocs directory is under the ColdFusion web
application root. For more information, see “Saving your ColdFusion page” on page 17.
ColdFusion MX installs two copies of the sample CompassTravel database file. The working copy
is located in the db directory; a backup copy of the file is in the new_user_database directory.
To ensure that you are working with the original database file, verify that the file in the db
directory has the same date as the backup file in the new_user_database directory. If the date of
the file in the db directory is later than the backup file, replace the file in the db directory with a
copy of the backup database.
Caution: Do not write to the database file in the new_user_database directory. The backup file lets
multiple users perform the tutorial.
In each of the database subdirectories, the tutorial provides one sample database file for Microsoft
Windows users and one sample database file for UNIX users. Windows users use a Microsoft
Access file, and UNIX users use a PointBase file.
Note: The sample PointBase file consists of two files: compasstravel.dbn and compasstavel$1.wal.
ColdFusion MX uses both of these files to work with the content in the sample PointBase database.
Save all the files that you create for the tutorial application in the my_app directory. This
directory contains one subdirectory for images. The image subdirectory contains the required
image files for the tutorial application.
The photos directory contains the required photo files for the tutorial application. The solutions
directory provides sample application files that you can use when building the tutorial
application.
Exercise 2: Setting up your development environment
If you are running ColdFusion in a Windows environment, Macromedia recommends that you
use Macromedia Dreamweaver MX for ColdFusion development; however, if you are running
ColdFusion in a UNIX environment, you should use the text editor that you prefer. Although
Dreamweaver MX offers features that help you create ColdFusion applications quickly and easily,
you can still follow the steps of the tutorial by entering or copying the code examples into your
editor.
Note: To use the Dreamweaver Extensions included with ColdFusion MX 7, you must use
Macromedia Dreamweaver MX 2004 version 7.0.1.
About Macromedia Dreamweaver MX
Macromedia Dreamweaver MX is the preferred development environment for building
ColdFusion MX 7 applications. It supports the latest ColdFusion MX 7 features, and it combines
superior code editing features with the visual design features of Dreamweaver. You can build
ColdFusion MX 7 applications by writing the code manually or generating the code by using one
of the code-generating tools provided with Dreamweaver MX. In addition, ColdFusion MX 7
provides extensions to Dreamweaver that let you perform some administrative tasks without
leaving the Dreamweaver environment and generate code for some of the most common tasks
you encounter when creating a ColdFusion application.
50Chapter 5: Lesson 2: Configuring Your Development Environment
With Dreamweaver MX, you can author and test your application code from a local or remote
client. You can save your code directly to the server computer where ColdFusion is installed. The
following sections provide an overview of Dreamweaver MX, and information on how to
configure Dreamweaver MX for ColdFusion development.
Features for ColdFusion developers
Dreamweaver MX provides a wide variety of code editing features for ColdFusion developers,
including the following:
• Extensions that generate code for common ColdFusion application tasks.
• Extensions that let you perform administrative tasks without leaving the Dreamweaver
environment.
• Rich tag editors for quickly setting attributes and values for every CFML tag.
• Code hints for writing CFML tag attributes.
• A code validator for validating code readiness against other ColdFusion versions.
• A tag chooser with integrated reference material for inserting ColdFusion tags.
• A snippets panel for reusing code.
• An integrated debugging display for quickly pinpointing problem areas in the code.
• A remote ColdFusion server connection for browsing remote data sources and files.
• ColdFusion MX documentation included in the Dreamweaver MX online Help.
To use Dreamweaver MX to build the sample ColdFusion application in this tutorial, see the
following sections for information about configuring Dreamweaver for ColdFusion development.
Configuring Dreamweaver MX for ColdFusion development
Before you use Dreamweaver MX to create the sample application in this tutorial, you must
configure Dreamweaver to use the ColdFusion MX 7 Extensions for Dreamweaver, which are
included with ColdFusion MX 7. You must also define the connection to the sample database
file. The Extensions simplify the process of configuring database connections.
To configure Dreamweaver MX to create the sample application:
1.
Install the ColdFusion MX 7 Extensions for Dreamweaver by double-clicking the
cfmx7dreamweaverextensions.mxp file, which is located in the cf_root/wwwroot/CFIDE/
installers directory.
2.
Create a site that contains the tutorial files.
3.
Specify ColdFusion as the application document type.
4.
Specify ColdFusion as the site application server technology. For information about how to
perform these steps, see the Dreamweaver MX online Help or Using Dreamweaver MX.
5.
Specify the RDS login information for the site.
Tip: If you are a new Dreamweaver MX user, you can perform the Dreamweaver MX tutorial before
using Dreamweaver MX to build the sample application. The tutorial in this book does not describe
how to use Dreamweaver. The purpose of this tutorial is to teach you how to build ColdFusion
applications using ColdFusion Markup Language (CFML).
Exercise 2: Setting up your development environment51
Exercise 3: Configuring a database connection
One of the most commonly used and most powerful features of ColdFusion is the ability to
connect to and manipulate data from a wide variety of databases. Like most ColdFusion
developers, you will probably use this capability often. To be able to connect to a database, you
must create a a data source in ColdFusion. A data source contains the information that
ColdFusion needs to be able to recognize and communicate with a database.
ColdFusion MX 7 includes a Dreamweaver extension that lets you create a data source without
having to leave the Dreamweaver environment. If you are not using Dreamweaver, you use the
ColdFusion Administrator to create data sources; see“Configuring a data source in the
Administrator” on page 52 for more information.
Using Dreamweaver to configure a data source
To create a ColdFusion data source without leaving the Dreamweaver environment, you need the
following information:
• The type of connection to use
• The name to call the data source
• The location of the database file(s)
To configure a database connection in Dreamweaver:
1.
Ensure that the site that contains the tutorial files is the current site.
2.
Select Create New > ColdFusion.
3.
On the Databases tab, click the + button.
4.
Select Microsoft Access Connection.
5.
In the CF Data Source Name text box, enter CompassTravel.
When prompted for the password for this site, enter the ColdFusion Administrator password
you specified when you installed ColdFusion MX 7.
9.
Click OK.
10.
Continue with “Exercise 4: Configuring debugging options” on page 55.
Configuring a data source in the Administrator
You can use the ColdFusion MX 7 Administrator to configure a data source. If you are running
ColdFusion in a UNIX environment, you must use the ColdFusion MX 7 Administrator to
connect to the PointBase database in the data source.
52Chapter 5: Lesson 2: Configuring Your Development Environment
To access the ColdFusion MX 7 Administrator:
• Open a browser and go to one of the following URLs:
■ External web server users: http://localhost/CFIDE/administrator
■ Built-in web server users: http://localhost:8500/CFIDE/administrator
■ J2EE server users: http://localhost:portnumber/CFIDE/administrator. If you installed
ColdFusion Enterprise Edition with JRun, the default HTTP port is 8300.
Note: If you are accessing the ColdFusion MX Administrator from a remote client, you must replace
localhost with the host name or IP address of the computer where ColdFusion MX is installed.
The following sections describe how to establish a connection to the sample tutorial database file
and how to enable optional debugging settings.
Configuring the connection to the sample database file
The following procedures describe how to configure a connection to the sample database file
(CompassTravel) using the ColdFusion MX Administrator. Prior to building the sample
application, you must configure the Compass Travel database connection.
Perform one of the following procedures. The Microsoft Access procedure is for Windows users.
The PointBase procedure is for UNIX and Macintosh OS X users.
To define the connection to the sample Microsoft Access database:
1.
In the ColdFusion MX Administrator, select Data & Services > Data Sources.
2.
In the Data Source Name box, enter CompassTravel.
3.
In the Driver list, select Microsoft Access with Unicode.
4.
Click Add.
5.
Click Browse Server and navigate to the cf_root/cfdocs/getting_started/db/CompassTravel.mdb
file.
6.
Click Apply.
7.
Click Show Advanced Settings and ensure that the settings for CLOB and BLOB are enabled
(checked).
8.
Click Submit to complete the data source configuration.
The ColdFusion MX Administrator verifies the data source connection and the name
CompassTravel appears in the Connected Data Sources table.
9.
Ensure that OK appears in the Status column for CompassTravel.
If the connection to the CompassTravel data source fails, do the following:
a
Verify that the name of the data source file does not contain a space. If it does contain a
space, delete the data source from the Connected Data Source dialog box. To do this, click
the Delete action button associated with the CompassTravel data source name, and then
repeat the steps in this procedure to reconfigure this data source.
b
Verify that the path specified for the Compass Travel database file is correct.
Exercise 3: Configuring a database connection53
To define the sample PointBase database file:
1.
In the ColdFusion MX Administrator, select Data & Services > Data Sources.
The Add New Data Source dialog box appears.
2.
Specify the following:
FieldAction
Data Source name
text box
Driver drop-down
selection box
3.
Click Add to configure the data source name and driver.
Specify the name CompassTravel.
Note: Ensure that the name of the data source file does not contain any
spaces. If the name contains a space, the data source connection fails.
Select Other.
The Data Source dialog box appears.
4.
Specify the following:
FieldAction
JDBC URLEnter the following JDBC URL for the Compass Travel PointBase files:
Click Show Advanced Settings to make the following settings:
FieldAction
Maintain ConnectionDisabled (clear)
CLOBEnabled (checked)
BLOBEnabled (checked)
6.
Click Submit to complete the data source configuration.
The name CompassTravel appears in the Connected Data Sources dialog box.
54Chapter 5: Lesson 2: Configuring Your Development Environment
7.
Click Verify All Connections to ensure that ColdFusion can access this file.
OK appears in the Status column for successful connections.
If the connection to the compass travel data source fails, do the following:
a
Verify that the name of the data source file does not contain a space. If it does contain a
space, delete the data source from the Connected Data Source dialog box. To do this, click
the Delete action button associated with the CompassTravel data source name, and then
repeat the steps in this procedure to reconfigure this data source.
b
Verify that the JDBC URL is correct.
Exercise 4: Configuring debugging options
ColdFusion provides debugging information to make it easier to fix problems in your application.
You can view debugging information for individual ColdFusion pages while editing them in
Dreamweaver, or enable debugging throughout your application by using the ColdFusion MX 7
Administrator to set debugging options.
Viewing debugging information within Dreamweaver
Instead of enabling debugging for an application, you can view debugging information for any
ColdFusion page in Dreamweaver.
To view debugging information for a ColdFusion page in Dreamweaver:
1.
Open the page to debug in Dreamweaver.
2.
On the Documents tab, click the Server Debug icon.
3.
If an Exceptions category appears in the Results panel, click the + button to expand the category.
4.
Fix the error and save the file, and click Browse.
5.
To leave debug mode, switch to either Code view or Design view.
Enabling debugging in the ColdFusion MX Administrator
The ColdFusion MX Administrator provides a variety of debugging settings that let you enable
debugging information on a server-wide basis. If you are working on a development system, you
can have these options turned on all the time. However, if you are working on a production
system, you most likely will not want to have these options turned on, because the debugging
information can appear on the bottom of an application page or in a dockable tree in
your browser.
Exercise 4: Configuring debugging options55
The location of the debugging information or the type of debugging data shown varies,
depending on the options that you enable on the Debugging page in the ColdFusion MX
Administrator. In the following example, the debugging output includes general information
about the ColdFusion server, the execution time of the application, and variable information:
The following figure shows an example of how debugging information can appear when
appended to the bottom of a page in a browser:
The application form
The appended debugging
information
If you are using a development server to build the sample application in this tutorial, you can
enable some of these settings to help debug any unexpected problems.
Use the following steps to enable debugging options in the ColdFusion MX Administrator.
To enable debugging options:
1.
In the ColdFusion MX Administrator, select Debugging & Logging > Debugging Settings.
A list of debugging options appears on the Debugging Settings page.
2.
Select the Enable Debugging check box.
The debugging service is enabled for all options already selected on the page.
3.
On the Debugging Settings page, view the description of each option that is enabled. If you do
not want to append debugging information for a specific option, clear the check box.
For the purpose of this tutorial, enable the following debugging options:
OptionDescription
Database ActivityIdentifies database activity related to SQL query events.
Exception InformationIdentifies ColdFusion exceptions raised in the debugging output.
Tracing InformationLets you trace event information reported in the debugging output.
Form, URL and Session
Variables
4.
Click Submit Changes when you are done.
56Chapter 5: Lesson 2: Configuring Your Development Environment
Displays variable information in the debugging output.
Sending debugging information to remote clients
If you are using a remote client to perform the tutorial in this book, you must specify your IP
address to receive debugging information. If you are working on a local client (the computer
where ColdFusion is installed), you do not need to do this.
To receive debugging information when using a remote client:
1.
In the ColdFusion MX Administrator, select Debugging & Logging > Debugging IP Addresses.
The Debugging IP Address page appears.
2.
In the IP Address text box, enter the IP address of your remote client.
3.
Click Add.
Summary
In this lesson, you set up your development environment, configured data sources, and set up
debugging options.
In the next lesson
In the next lesson, you learn to retrieve data from a database, display the results of querying a
database, and use ColdFusion components to write structured, reusable code.
Summary57
58Chapter 5: Lesson 2: Configuring Your Development Environment
CHAPTER 6
Lesson 3: Retrieving Data
In this lesson, you begin the construction of a Macromedia ColdFusion web application for the
fictitious company, Compass Travel. The exercises in this lesson introduce you to the process of
retrieving data from the Compass Travel relational database.
As you recall from “Lesson 1: Preparing to Build the Sample Application” on page 41, one of the
requirements for the Trip Maintenance application is the ability to generate trip listings. To help
Compass Travel agents take trip reservations by telephone and in person, the trip coordinator
maintains a list of current trip offerings. Years ago, the coordinator would type the list and fax it
to the various Compass Travel offices in an effort to keep everyone informed. When Compass
Travel built an intranet that was accessible by all offices, the trip coordinator added the following
HTML web page to the site:
Each time the Trip List HTML page is rendered in a browser, it displays the same web page. Since
the page always shows an identical trip list, it is considered a static web page. You should only use
static web pages when you are creating a page that is not likely to change often.
Using the static web page approach, the Trip Coordinator needs to modify all the web pages that
reference trip lists when trips are added, deleted, or trip names are changed. This manual process
of updating each web page can lead to inaccurate or untimely information. Luckily, Compass
Travel has built a database that contains a list of trips, so you can build a more accurate and timely
solution for the trip coordinator.
In this lesson, you will create a dynamic Trip List page to present an up-to-date list of trips on the
Compass Travel website. The primary users of this component are the Compass Travel
coordinators and agents, not the general public.
To display the information on the page, you do the following:
1.
Retrieve the data that you want to display.
2.
Display the data on the page.
60Chapter 6: Lesson 3: Retrieving Data
Exercise 2: Retrieving the information for the trip list
Relational database management systems process SQL instructions sent to them from various
applications. ColdFusion sends SQL statements to database managers to manipulate data.
ColdFusion needs a way to know to which database manager to send a specific SQL string for
evaluation. In CFML, the
statement and the
cfquery tag to create a dynamic version of the Trip List page described earlier
in this lesson. In this example, you use the
tripName column in the Compass Travel Trips table. To use the SQL SELECT statement to
dynamically retrieve this information, you must execute the SQL SELECT statement between the
cfquery start and end tags.
To retrieve the trip list:
1.
If you are working in Dreamweaver, ensure that the site that you created in Lesson 1 is the
current site. For more information, see “Configuring Dreamweaver MX for ColdFusion
development” on page 51.
2.
Open a new file and save it as triplisting.cfm in the my_app directory.
Note: If you are working in Dreamweaver, ensure that you select ColdFusion Templates in the
Save As Type list.
3.
Enter the following code, or do the steps listed in the “Let Dreamweaver do it” section.
cfquery tag serves this purpose. You will use the SQL SELECT
cfquery tag to return all the trip names found in the
Let Dreamweaver do it
Dreamweaver lets you create a query without having to enter the code.
To create a query in Dreamweaver:
1.
Click the Bindings tab in the application panel.
2.
Click the + button.
3.
Select Recordset (Query).
4.
In the Name text box, enter Tr i p L i s t .
5.
From the Data source list, select CompassTravel.
6.
From the Tables list, select trips.
7.
Next to Columns, click Selected.
8.
Select tripName.
9.
Click OK.
10.
Save the file.
Your ColdFusion application page retrieves the information for the trip list. Next, you need to
display the information.
Exercise 2: Retrieving the information for the trip list61
Reviewing the code
The following table describes the code used to build the query:
Code Explanation
<cfquery name="TripList"
datasource="CompassTravel">
SELECT trips.tripName FROM
trips
ColdFusion query named TripList. Submits any SQL statement
between the
specified in the
SQL SELECT statement to retrieve all tripName(s) from the trips
table.
cfquery start and end tags to the data source
datasource attribute.
Exercise 3: Displaying the query result using the cfoutput tag
In Chapter 2, “CFML Basics,” on page 15, you learned that the ColdFusion cfoutput tag is an
easy mechanism to display literal text and the contents of variables. Additionally, the
tag significantly simplifies displaying the results of queries. When used to display the results from
a query, the
the name of the query in the
<cfoutput query="TripResult">
cfoutput tag automatically loops through the record set for you. You simply specify
query attribute of the cfoutput tag:
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>
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:
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.
Exercise 4: Writing structured, reusable code
Generally, it is good coding practice to separate business logic from the display. The ColdFusion
page that you just created contains both business logic (the database query) and presentation (the
output code block). To separate them, you put the query in a ColdFusion component (CFC).
Doing so separates business logic from presentation; it also makes it easy to reuse the query
anywhere in your application. For more information, see Chapter 10, “Building and Using
ColdFusion Components” in ColdFusion MX Developer’s Guide.
To move the query to a CFC:
1.
Create the CFC file.
2.
Copy the query to the CFC.
3.
Call the method that contains the query.
Creating the CFC file
ColdFusion components (CFCs) are special files saved with the filename extension .cfc. They can
contain data and functions. Within CFCs, functions are referred to as methods. Actions that you
want ColdFusion to perform, such as querying a database, are contained in component methods.
One CFC can contain many methods. Each method in a CFC can return only one variable. The
following is the general syntax of a CFC:
<cfcomponent>
<cffunction name="firstMethod">
<!--- CFML code for this method goes here. --->
</cffunction>
<cffunction name="secondMethod">
<!--- CFML code for this method goes here. --->
</cffunction>
</cfcomponent>
Exercise 4: Writing structured, reusable code63
To create the CFC file:
1.
Create a directory named components as a subdirectory of the my_app directory.
2.
Open a new blank file.
Note: If you are using Dreamweaver, select Dynamic page in the Category list, and select
ColdFusion Component in the Dynamic Page list.
3.
Enter the following code, or do the steps listed in the “Let Dreamweaver do it” section.
displayName="List all trips" hint="List trips in same order as in table"
access="public" returnType="query" output="false">
<cfquery name="TripList" datasource="CompassTravel">
SELECT trips.tripName FROM trips
</cfquery>
<cfreturn>
</cffunction>
</cfcomponent>
3.
Modify the code by adding the f ollowing t ext so that the method returns the results of the query
to the triplisting.cfm page:
<cfreturn TripList>
4.
Save the gettrips.cfc file.
Calling the query method
To perform the query that is now in a method in a ColdFusion component, you have to call
(invoke) the method. To do so, you can use the
cfinvoke tag. Within the cfinvoke tag, you
specify the name of the ColdFusion component, the method to call, and the query to return to
the calling page. The name of the component includes the package,
"cfdocs.getting_started.my_app.components." The package looks very similar to the path, except
that it contains periods instead of slashes. Like a path, it specifies the location of the component.
To invoke the method:
1.
Go to the top of the triplisting.cfm file.
2.
Enter the following code, or do the steps listed in the “Let Dreamweaver do it” section.
View the triplisting.cfm page in a browser and notice that the page lists the trip names, just as
it did previously.
Exercise 4: Writing structured, reusable code65
Let Dreamweaver do it
Dreamweaver lets you invoke a method in a CFC without having to write the code.
To invoke the method using Dreamweaver:
1.
Click the Components tab in the Application panel.
2.
Click the + button next to cfdocs.getting_started.my_app.components.
3.
Click the + button next to gettrips.
4.
Select query basicList() and drag it to the top of the triplisting.cfm file.
5.
Change the value of the returnvariable to be the name of the query, TripList, as follows:
returnvariable="TripList"
6.
Return to Step 3 in the “To invoke the method:” procedure.
Exercise 5: Creating additional queries
In this exercise, you will improve the Trip List page to make it easier for the Compass Travel
agents to locate trips. You must make the following improvements:
• Sort the trip names in alphabetical order.
• Display the departure date, return date, and price for each trip.
• Develop a Budget Trip List report that identifies trips that are priced $1500 or less.
You could modify the existing query; however, you may need to use that query in the future.
Instead, you can create an additional method in the gettrips.cfc component with a query that
meets the preceding requirements. You can then call the new methods with the enhanced query
from the triplisting.cfm page. Display the triplisting.cfm page in the browser after each step to
ensure that the corresponding requirement was met.
To modify the application, you must:
• Create the query that meets the requirements.
• Invoke the method that contains the query.
• Display the results.
Creating the query
To continue writing structured, reusable code, you create the query in a method in the existing
CFC.
To create a method with enhanced query results:
1.
Open the gettrips.cfc file.
2.
Enter the following code just before the closing cfcomponent tag, or do the steps in the “Let
Change the heading tag in the triplisting.cfm file from <h1>Trip List</h1> to <h1>Budget
Trip List</h1>.
68Chapter 6: Lesson 3: Retrieving Data
cfoutput block and
3.
Save both the triplisting.cfm file and the gettrips.cfc file.
4.
View the triplisting.cfm page in a browser and verify that all the new requirements were met.
The revised TripListing.cfm page looks like this:
The dates and prices in the preceding listing are not formatted. In “Lesson 6: Creating a Main
Application Page” on page 97, you will enhance the look of this page.
Summary
This lesson described how to access a relational database using ColdFusion. You used the SQL
SELECT statement and the
use ColdFusion components to write structured, reusable code.
cfquery and cfoutput tags to display trip lists. You also learned to
In the next lesson
In the next lesson, you will build the search form to let users select which information to retrieve.
To build the query based on what the user enters in the search form, you will use dynamic SQL.
You will then display the results of the search on an action page.
Summary69
70Chapter 6: Lesson 3: Retrieving Data
CHAPTER 7
Lesson 4: Building Dynamic Queries
In this lesson, you develop a search form to allow users to select the information to retrieve, and
then display, the search results.
As you recall from “Lesson 1: Preparing to Build the Sample Application” on page 41, two of the
requirements for the Trip Maintenance application are the ability to generate trip listings and a
trip query facility. You will create a search interface that meets both of these requirements in this
exercise.
About the trip search form
The dynamic listings that you developed in “Lesson 3: Retrieving Data” meet many of Compass
Travel’s requirements for locating trips. However, what if the number of trips were in the
thousands or tens of thousands? Locating the right trip for a customer might be difficult and
certainly time consuming. Moreover, it is very hard, if not impossible, to anticipate all the ways
that a user might want to search for trips.
71
A better solution is to provide an interface for the user to specify the search criteria. The purpose
of the Trip search form is to enable Compass Travel employees to search and view brief details
about existing trips on their website. The completed form should appear as follows:
Designing the search criteria page
When designing the search criteria page, it is a good idea to develop a list of possible queries that
the user might issue when searching for the records. Most Compass Travel customers are
primarily concerned with trip locations, departure dates, and price; the following is a list of the
types of queries that the agents are likely to require at Compass Travel:
• List the trips located in Hawaii.
• Identify the trips with a price greater than $3,000.
• Show the trips departing after 11/11/2005 that are priced less than $2,000.
There are a number of considerations to take into account when you design a search page to
capture the user’s search criteria. The following are two of the most important considerations:
• For which database columns will the user be allowed to specify a search condition?
• Should the user be allowed to identify which database columns to include in the record set?
In this exercise, the Compass Travel trip coordinator searches the trips based on tripLocation,
departureDate, and price. Because these columns are the only ones that users can query, they are
the only ones contained in the WHERE clause of the generated SQL statement. In addition, the
coordinator has no control over which columns are returned in the record set. The query always
returns the same columns to identify a trip:
• tripName
• tripLocation
• departureDate
• returnDate
• price
• tripID
72Chapter 7: Lesson 4: Building Dynamic Queries
In later exercises, you will reference these columns when you build the SQL SELECT statement
for the
cfquery in the search action page.
Understanding search query operators
Now that you have decided which columns can be queried (tripLocation, departureDate, and
price), you can build a simple form that lets the user enter values for each of these fields. If the
user enters a value (for example, Boston) for the tripLocation field and leaves the other two fields
blank, the search results page constructs the following SQL statement:
SELECT tripName, tripLocation, departureDate,
returnDate, price, tripID
FROM trips
WHERE tripLocation = 'Boston'
When you design the Search Criteria page, you must decide which operators to support for each
of the columns you can query. The operators that you use depend on the data type of the SQL
column.
For example, suppose the user wants a list of all the trips where the trip location begins with a
"B." SQL is well-suited for this type of query. Typical SQL string operators are equals, starts with, contains, and ends with.
However, price is a numeric data type. The user can specify any of the following:
• Price is 5000
• Price less than 600
• Price greater than 1500
Although many more operators are permissible, for simplification, you can use the following
operators for the Compass Travel columns that you can query:
Column to queryQuery operators
tripLocationis, begins with
departureDateis, before, after
priceis, greater than, less than
Creating the Trip Search page
A simple design for a search criteria page presents an operator list and data entry field for each of
the columns that you can query. To create the search criteria page, you create an HTML form.
To create the search page:
1.
Create a blank file.
Note: If you are using Dreamweaver, select Dynamic page in the Category list and ColdFusion in
the Dynamic Page list.
2.
Enter, or copy and paste, the following code in the blank file:
Save the file as tripsearchform.cfm in the my_app directory.
Reviewing the code
The following table describes the search criteria code and its function:
Code Explanation
<form action="tripsearchresult.cfm"
method="post">
<select name="tripLocationOperator">
<option value="EQUALS">is
<option value="BEGINS_WITH">begins with
</select>
<input type="text" name="tripLocationValue">
Identifies tripsearchresult.cfm as the search
action page. Results of user entry are passed
to the search action page.
Builds a drop-down list offering the query
operators for tripLocation. There must one
operator list box for each queryable column.
Captures a value to test. There is one text
control for each queryable column.
Exercise 2: Building a query that uses dynamic SQL
Dynamic SQL is a term that refers to SQL code that your program generates using variables before
the SQL is executed. You can use dynamic SQL to accomplish tasks such as adding WHERE
clauses to a search based on the fields that the user filled out on a search criteria page.
Based on the columns that you can query in this tutorial, the SQL query to display the search
results would look like this:
SELECT tripName, tripLocation, departureDate, returnDate, price, tripID
FROM trips
The purpose of the Trip Search form is to supply the data needed to build the WHERE clause to
finish this SQL SELECT statement and constrain the query according to the user’s input.
When the user enters the search criteria on the Trip Search form and clicks the Search button, the
form fields are posted to the Trip Search Results page. The posted field values compose the
WHERE clause in the SQL SELECT statement. The following example lists the WHERE clauses
that you can generate depending on the criteria set on the search page:
WHERE tripLocation = 'Aruba'
WHERE tripLocation Like 'C%'
WHERE tripLocation = 'China'
AND departureDate > 1/1/2001
AND price < 1500
In this example, the SQL AND operator joins the search condition clauses. To simplify the trip
search example, you will use the SQL AND operator to combine all the search condition clauses.
A more sophisticated search criteria page might present the user a choice of using AND or OR to
connect one search criterion with the others.
Exercise 2: Building a query that uses dynamic SQL75
The action page invokes a method that builds the WHERE clause so that the SQL SELECT
statement retrieves the information that the user requests. Then, the action page displays an
HTML table with the results of the user query using the
cfoutput block.
Building the WHERE Clause with the cfif and cfset tags
The WHERE clause in a SQL SELECT statement is a string. You use the CFML
cfset and cfif
tags to conditionally build the WHERE clause depending on values passed to the search action
page. The
cfset statement creates a variable or changes the value of an existing variable. For
example, to create a variable named color and initialize its value to red, you use the following
statement:
<cfset color = "red">
The cfif tag instructs the program to branch to different parts of the code depending on
whether a test evaluates to True or False. For example, to have some code execute if the color
variable is equal to red, and other code execute if it is not, you use the following pseudocode:
<cfif color EQ "red">
... statements for color red
<cfelse>
... statements for other than red
</cfif>
Buildinga SQL WHERE clause in code is largely an exercise in string concatenation. The &
operator combines two strings in ColdFusion. For example, the following code snippet:
<cfset WhereClause = WhereClause & " AND tripLocation like '" &
form.tripLocationValue & "%'" >
</cfif>
When you test for a string column within the WHERE clause of the SQL SELECT statement,
you must enclose the test value in quotation marks.
When you use a variable to construct a WHERE clause, you must preserve the quotation marks
so that the database server does not return an error. To preserve the quotation marks, you must
use the ColdFusion
PreserveSingleQuotes function. The PreserveSingleQuotes function
prevents ColdFusion from automatically escaping single-quotation marks contained in the
variable string passed to the function.
Note: The cfqueryparam tag also escapes single-quotation marks. For more information, see CFML
Reference.
Creating the CFC query
The following code shows how to construct the tripLocation SQL WHERE subclause.
Specifically, it uses a dynamic SQL SELECT statement built from parameters from the Trip
Search page to display the search results. To continue the good coding practice of separating
business logic and presentation, you put the code to build the query using dynamic SQL in a
function in the CFC that you have been working with.
To add the new query to the CFC:
1.
Open the file gettrips.cfc file and position the pointer before the closing cfcomponent tag.
2.
Enter the following code, or do the steps in the “Let Dreamweaver do it” section:
<!--- Create WHERE clause from data entered via search form --->
<cfset WhereClause = " 0=0 ">
<!--- Build subclause for trip location --->
<cfif Form.tripLocationValue GT "">
You can use the Dreamweaver Extensions to create the CFC query.
To construct the query with Dreamweaver:
1.
Click the Bindings tab.
2.
Click the + button.
3.
Select Record set (Query).
4.
In the Name text box, enter Tr i p R e s u l t .
5.
Click the New Function button.
6.
In the New function name text box, enter getTripsFromForm and click OK.
7.
From the Data source list, select CompassTravel.
8.
From the Tables list, select trips.
9.
Click the Selected radio button.
10.
Select tripName, tripLocation, departureDate, returnDate, price, and tripID.
11.
Click OK.
12.
Return to Step 3 in the “To add the new query to the CFC:” section.
78Chapter 7: Lesson 4: Building Dynamic Queries
Exercise 3: Constructing the initial Trip Search Results page
After the user enters the search criteria and submits the form, the results are posted to the Trip
Search Results page, as the following figure shows:
The logic contained in the search results page, also known as the action page, invokes the CFC
method that builds the SQL SELECT statement contained in a
ColdFusion string manipulation. The action page displays the result using the
To create the Trip Search Results page:
1.
Create a blank document and save it as tripsearchresult.cfm in the my_app directory.
Note: If you are using Dreamweaver, select Dynamic page in the Category list, and ColdFusion in
the Dynamic Page list.
2.
Enter the following code, or do the steps in the “Let Dreamweaver do it” section.
As you have in previous exercises, you can let Dreamweaver generate the code to invoke the
method.
To invoke the method using Dreamweaver:
1.
Click the Components tab.
2.
Click the + button next to cfdocs.getting_started.my_app.components.
3.
Click the + button next to gettrips.
4.
Select query getTripsFromForm() and drag it to the top of the triplisting.cfm file.
5.
Change the value of returnvariable to be the name of the query, TripResult, as follows:
returnvariable="TripResult"
6.
Return to Step 3 in the “To create the Trip Search Results page:” section.
Reviewing the code
The following table describes the code used to build the tripLocation WHERE subclause:
Code Explanation
<cfset WhereClause = " 0=0 ">
80Chapter 7: Lesson 4: Building Dynamic Queries
The cfset tag initializes the WhereClause variable to
hold the WHERE clause to be constructed. The
initial value is set to
clause has at least one subclause in case the user
enters no search criteria.
" 0=0 " so that the WHERE
Code Explanation
<cfif Form.tripLocationValue GT "">
SELECT tripName, tripLocation,
departureDate, returnDate, price, tripID
FROM trips
WHERE #PreserveSingleQuotes(WhereClause)#
The
cfif tag tests to see if the user entered anything
in the Value input field for tripLocation criterion.
SQL query to execute. The PreserveSingleQuotes
function ensures that quotation marks are passed to
the database server as intended.
The preceding code only builds the tripLocation subclause. In the following exercise, you will add
code for the other two columns that you can query, departureDate and price.
Exercise 4: Testing the Trip Search Results page
In this exercise, you will test the tripsearchresults.cfm page. First, you will test the Trip Search
Results page by entering criteria on the Trip Search form and inspecting the results. Next, you will
finish the code to construct the complete WHERE clause for all three columns that you can
query from the Trip Search form.
To test the Trip Search Results page:
1.
View the tripsearchform.cfm page from the my_app directory in your browser and do the
following:
a
In the Trip Location drop-down list, select the Begins With option, and enter the value C in
the text box.
b
Click Search.
The Trip Results page displays several entries, as follows:
c
Notice in the Trip Results page that only one trip has a trip location of China.
d
Click the Back button in your browser to return to the Trip Search page.
2.
In the Trip Location drop-down list of the Trip Search page, select the Is option, enter the value
China, and then click Search.
The Trip Search Results page displays only one entry for the trip to China in the HTML table.
Exercise 4: Testing the Trip Search Results page81
3.
Verify that the other criteria (departure date and price) are not taken into consideration yet as
follows:
a
Click the Back button in the browser to return to the Trip Search page.
b
In the Departure Date drop-down list box, select Before, enter 1/1/1900 as the date, and
select Smaller Than 0 for the price.
Either of these conditions would produce a results page with no rows.
c
Click the Search button.
The Trip Search Results page should be identical to the one in Step 2, because the code to
build the WHERE clause in the Trip Search Results page does not include departure date
and price.
Exercise 5: Enabling the departure and price criteria on the Trip
Search form
In this exercise, you will modify the Trip Search Results page to add the criteria needed for the
departure and price query.
To enable the departure and price criteria:
1.
Open the gettrips.cfc file.
2.
In the getTripsFromForm method, position the pointer before the cfquery code block.
3.
To build the departureDate WHERE subclause, enter or copy and paste the code in the
following table immediately before the
Exercise 6: Testing the revised Trip Search Results page
In this exercise, you will verify that the price and departureDate are now considered in the
query.
To test the revised Trip Search Results page:
1.
Open the tripsearchform.cfm page in the my_app directory in your browser.
2.
In the Departure Date drop-down list box, select Before, enter 1/1/1900 as the date (specify
1900-1-1 on UNIX).
3.
Select Smaller Than, and enter 0 for the price.
4.
Click the Search button.
Because the departure date is considered in the query, there are no rows returned.
Note: If you planned to use many more fields as search criteria, the approach used to add
departure date and price criteria to the Trip Search form is not the most elegant solution. A generic
routine to handle WHERE clause string construction based on specific data types could reduce
the code and be a more extensible solution than the one presented here. However, this more
extensible approach is beyond the scope of this tutorial.
Summary
This lesson described how to build a search tool that dynamically builds a WHERE clause of the
SQL SELECT statement using
intact, you used the
PreserveSingleQuotes CFML function.
In the next lesson
In the next lesson, you will build the Trip Detail page, which will display detailed information
about the currently selected trip.
cfif and cfset tags. To ensure that the SQL statement remains
Summary83
84Chapter 7: Lesson 4: Building Dynamic Queries
CHAPTER 8
Lesson 5: Creating a Trip Detail Page
In this lesson you will enhance the Compass Travel Trip Maintenance application. This lesson
contains the following exercises:
Exercise 2: Avoiding the potential security risk when using dynamic SQL . . . . . . . . . . . . . . . . 91
Exercise 3: Linking the Trip Search Results page with the Trip Detail page . . . . . . . . . . . . . . . 92
Exercise 4: Enhancing the look of the Trip Search Results and Trip Detail pages . . . . . . . . . . . 93
ColdFusion tags and functions introduced in this lesson
The following table describes the ColdFusion tags and functions that you use in this lesson to
enhance the sample ColdFusion application:
ElementTypeDescription
DollarFormat
DateFormat
IsDefined
URLEncodedFormat
FunctionReturns a number as a String formatted with two decimal
places, a thousands separator, and a dollar sign. If the
specified number is negative, parentheses are used.
FunctionReturns a formatted date-time value. If no mask is specified,
the
DateFormat function returns the date value in the dd/
mmm/yy format. The
have the U.S. date format.
FunctionEvaluates a String value to determine whether it represents
an existing variable. Returns True if the variable is found,
False if not found.
FunctionConverts a text string into a String that you can safely use in a
URL.
DateFormat function supports dates that
85
Exercise 1: Creating a Trip Detail page
By design, the Trip Search Results page displays a subset of the information about a trip. To get
additional information about any of the trips, the user should be able to click any row to display
the detailed trip data.
In this exercise, you build a Trip Detail page to provide all the information about a particular trip
that is stored in the Compass Travel trips database. The following figure shows an example of the
Trip Detail page that you build:
After you complete the Trip Maintenance application in this tutorial, you will use this Trip Detail
page in several ways:
• You can call the Trip Detail page directly by typing in the address of the page with an ID. For
example, to view trip information for Rio Cahabon Rafting with tripID 24, you open a
browser and enter the following URL:
• You can navigate to the Trip Detail page by creating a hyperlink from the trip name on the Trip
Search Results page. This will offer the user drill-down capability when searching for trips. You
will link the Trip Search Results page and the Trip Detail page in one of the exercises in this
lesson.
• You can use browse buttons on the Trip Detail page to navigate the Trips table row-by-row.
You will implement this navigational feature in “Lesson 6: Creating a Main Application Page”
on page 97.
Building the Trip Detail page
To build the Trip Detail page, you do the following:
• Create a CFC that queries the database.
• Create the Trip Detail page, which invokes the CFC query and displays the results of the query.
86Chapter 8: Lesson 5: Creating a Trip Detail Page
To build the CFC query:
1.
Create a blank ColdFusion page.
2.
Save the file as tripdetail.cfm in the my_app directory.
3.
Perform the following steps, or do the steps in the “Let Dreamweaver do it” section.
The cfcomponent tag creates a CFC. The cffunction tag
creates a method named
method returns the results of the query to the calling page.
The cfquery tag includes a maxRows attribute. This attribute
limits the number of result rows brought back from the
database. In the Trip Detail page, you want to show only a
single row at a time; therefore, the
to
1.
The URL.ID specifies a parameter that you can include in
the URL that requests this page. If the ID parameter is
passed within the URL, it is used in the SQL query to
identify the
IsDefined function to determine if a parameter is passed
within the URL. You can also use
the user has entered data in form fields prior to the form
post action.
tripID to SELECT. You can use the CFML
getTripDetails in the CFC; the
maxRows attribute is set
IsDefined to determine if
As you did in this exercise, you can build comprehensive database query applications using
CFML and dynamic SQL. To further test the new Trip Detail page that you created, you will link
it to the search facility that you built in Lesson 4: Building Dynamic Queries. However, before
you link that search facility, you must understand a potential security risk using dynamic SQL.
The following exercise describes this risk and how to avoid it.
Exercise 2: Avoiding the potential security risk when using
dynamic SQL
To reduce round trips between the client and the database server, many SQL database servers
permit the client to submit multiple SQL statements in a single request, separated by a
semicolon (;). For these database managements systems, the following SQL request is valid:
DELETE from trips where tripLocation = 'China'; SELECT tripName from trips
This request might be an efficient way to list the trips that remain after the database management
system removes the China trip. Problems arise when the SQL statement is built dynamically.
In the Trip Maintenance application, when the client program or user passes an ID in the URL
that calls the Trip Detail page, the page displays the relevant trip information. The following code
builds the correct WHERE clause that supports this behavior:
<cfif IsDefined("URL.ID")>
WHERE tripID = #URL.ID#
</cfif>
Exercise 2: Avoiding the potential security risk when using dynamic SQL91
If a user called the Trip Detail page using the following statement:
the SQL database management system executes the proper SQL SELECT statement, and then
immediately erases the Trips table from the database.
Protecting your application
To ensure that your application is protected from such an attack, you can exploit the fact that the
ID must be a numeric value. The CFML
of a string expression. You can use the
<cfif IsDefined("URL.ID")>
WHERE tripID = #Val(URL.ID)#
</cfif>
Val function returns the numeric value at the beginning
Val function as follows:
If nonnumeric data is passed within the URL ID field, the Val function returns 0, and the trip
with ID 0 appears (if one exists). If the user enters the previously cited URL
(http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24;DROP+trips), the
application ignores the non-numeric values and displays the trip information of trip ID 24.
Warning: The exercises in this tutorial ignore the dynamic SQL risk from attack. To eliminate this risk,
you should use ColdFusion functions (such as
For queries, you can also use the
cfqueryparam tag, which is explained in CFML Reference.
Val) to perform type checking on all URL parameters.
Exercise 3: Linking the Trip Search Results page with the Trip
Detail page
In this exercise, you will modify the Trip Search Results page to let the user view the details of any
trip. To do this, you will convert each trip name entry in the results page to a link, which will
display the trip’s detailed information in the detail page.
Use the following steps to link the Trip Search Results page (tripsearchresult.cfm) to the Trip
Detail page (tripdetail.cfm).
To create links between the Trip Search Results page and the Trip Detail page:
1.
Open the tripsearchresult.cfm file from the my_app directory.
2.
Replace #tripName# in the cfoutput block with the following code:
Note: The
are replaced with %20, and nonalphanumeric characters with equivalent hexadecimal escape
sequences. The function lets you pass arbitrary strings within a URL, because ColdFusion
automatically decodes URL parameters that are passed to the page.
3.
Save the file.
92Chapter 8: Lesson 5: Creating a Trip Detail Page
URLEncodedFormat is a ColdFusion function that returns a URL-encoded string. Spaces
To test the revised page:
1.
View the tripsearchform.cfm page from the my_app directory in your browser.
2.
In the Trip Location drop-down list, select Begins With, and enter the value C.
3.
Click Search.
The Trip Search Results page displays a hyperlink for each trip name, as the following figure
shows:
4.
To view the Trip Detail page for a trip, click the trip name.
You might notice that the dates and prices in both the Trip Detail and Trip Search Results pages
are unformatted. You will improve the appearance of the application in “Exercise 4: Enhancing
the look of the Trip Search Results and Trip Detail pages” on page 93.
Exercise 4: Enhancing the look of the Trip Search Results and
Trip Detail pages
The Trip Maintenance application now provides a useful drill-down mechanism for locating trips.
Although this application is functionally sound, its appearance could be improved, including
formatting dates and dollar amounts, and making long lists easier to read.
Formatting dates and dollar amounts
ColdFusion provides several functions to improve application appearance. These include the
DateFormat and DollarFormat functions that format dates and currency variables.
To format the dates and dollar amounts:
1.
To format the Trip Detail page dollar and date fields, open the tripdetail.cfm file in the my_app
directory in your editor and make the following changes:
Exercise 4: Enhancing the look of the Trip Search Results and Trip Detail pages93
2.
Save the file.
3.
To format the currency and date fields on the Trips Search Results page, open the
tripsearchresult.cfm file in your editor and make the changes for
and
price indicated in the table.
4.
Save the file.
To view the application’s new appearance:
1.
View the tripsearchform.cfm page in the my_app directory in your browser.
2.
In the Trip Location drop-down list, select Begins With and enter the value C.
3.
Click Search.
departureDate, returnDate,
The Trip Search Results page appears:
4.
In the Trip Search Results page, click the link for Riding the Rockies.
The properly formatted Trip Detail page appears:
94Chapter 8: Lesson 5: Creating a Trip Detail Page
Summary
In this lesson, you transformed the search facility that you built in “Lesson 4: Building Dynamic
Queries” into a drill-down facility for trip queries. You built a Trip Detail page to show more
information about a particular trip. You also formatted the Trip Search Results and Trip Detail
pages using the CFML
Results page with the Trip Detail page.
In the next lesson
In the next lesson, you will add navigation and maintenance buttons on the main Trip
Maintenance application page.
DateFormat and DollarFormat functions. You linked the Trip Search
Summary95
96Chapter 8: Lesson 5: Creating a Trip Detail Page
CHAPTER 9
Lesson 6: Creating a Main Application Page
In this lesson you will enhance the Compass Travel Trip Maintenance application. So far, you
created a very useful drill-down query facility. Compass Travel trip coordinators can produce lists
required by management and easily locate and display information about any trip. There are
several requirements that were identified in “Lesson 1: Preparing to Build the
Sample Application” on page 41 that you have not yet addressed:
• The ability to browse through the Trips table.
• The ability to add, delete, and edit trip information.
You will modify the Trip Detail page to accomplish this additional functionality. The Trip Detail
page shows information about a single trip. You will convert the Trip Detail page into the main
application page by adding the following functionality:
• Navigation buttons to browse the database
• Database maintenance buttons to edit, delete, and add new trips, as well as a button to search
This lesson contains the following exercises:
Exercise 1: Creating the main application page from the Trip Detail page . . . . . . . . . . . . . . . . 98
Exercise 1: Creating the main application page from the Trip
Detail page
In this exercise, you convert the Trip Detail page into the main Trip Maintenance application
page. The main application page includes additional buttons for navigating to other ColdFusion
pages and browsing the trip database records.
Maintenance buttons
Trip detail information that you build initially
Navigation buttons
Adding navigation buttons to browse the database
The drill-down search function developed in “Lesson 5: Creating a Trip Detail Page” on page 85
is very useful when the user knows some search criteria to enter. Flipping back and forth between
the results page and the detail page to navigate through a record set can be tedious. Moreover, on
occasion the trip coordinator might want to browse the Trips database just to check for anomalies
or to become familiar with its contents. In these cases, the trip coordinator does not know the
criteria to search for in advance.
The following figure shows the navigation buttons. The label below each button does not appear
in the application; it describes which row to display relative to the currently displayed row.
98Chapter 9: Lesson 6: Creating a Main Application Page
To add navigation buttons to the Trip Detail page:
1.
Open the tripdetail.cfm file in the my_app directory.
2.
Insert the following code between the </table> and </cfoutput> tags:
Note: The current trip record ID (
action page with current record ID that it must have in order to build the query to access the
appropriate record in the Trips database table.
3.
Save the file.
To test the updated application:
1.
View the updated tripdetail.cfm page in a browser.
tripID) is in a hidden field in the form code. This field provides the
The Trip Search Results page appears:
2.
Test the buttons by clicking any navigation button.
An error occurs because the navigation action page (navigationaction.cfm) does not exist. The
navigation action page processes the navigation button requests. You will build the navigation
action page in “Lesson 7: Validating Data to Enforce Business Rules” on page 103.
Exercise 1: Creating the main application page from the Trip Detail page99
Reviewing the code
The following table describes the navigation code for the Trip Detail page:
Form tag that identifies the
navigationaction.cfm file to handle
record navigation.
Hidden RecordID field with the value of
the current
Navigation buttons that are image type
HTML input tags.
tripID.
Exercise 2: Adding database maintenance buttons
The search and sequential navigation capabilities are features for locating Compass Travel trips.
After locating a trip, the trip coordinator must be able to modify or delete it. Additionally, when
viewing the detail for a trip, the trip coordinator must be allowed to add a new trip or use the
search facility. To enable trip coordinators to do this, you add the following buttons to the Trip
Detail page:
As described in “Exercise 1: Creating the main application page from the Trip Detail page”
on page 98, it is important to pass the current record ID (
tripID) to the action page to build the
proper SQL statement to process the navigation button requests. It is also important to pass the
current record ID to the Maintenance Action page. Therefore, you use an HTML
hide the current
To add maintenance buttons:
1.
Open the tripdetail.cfm file from the my_app subdirectory.
2.
Enter the following code immediately after the <cfoutput query="TripQuery"> tag:
Note: The current trip record ID (
action page with current record ID that it must have in order to build the query to access the
appropriate record in the Trips database table.
3.
Save the file.
100Chapter 9: Lesson 6: Creating a Main Application Page
recordID and post it to the maintenanceaction.cfm page.
tripID) is in a hidden field in the form code. This field provides the
input tag to
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.