Cover | Table of Contents | Colophon
http://www.autobytel.com/)
Williams-Sonoma's storefront application (http://www.williams-sonoma.com/), and
Infonautics's Company Sleuth application for tracking publicly
traded companies (http://www.sleuth.com/).
http://www.autobytel.com/)
Williams-Sonoma's storefront application (http://www.williams-sonoma.com/), and
Infonautics's Company Sleuth application for tracking publicly
traded companies (http://www.sleuth.com/).
http://www.allaire.com (as of this writing,
the latest release of ColdFusion is Version 5.0):
<HTML> <HEAD> <TITLE>CFML Example</TITLE> </HEAD> <BODY> <CFOUTPUT> <H2>Today's date is #DateFormat(Now( ),'mm/dd/yyyy')#</H2> </CFOUTPUT> </BODY> </HTML>
<HTML> <HEAD> <TITLE>CFML Example</TITLE> </HEAD> <BODY> <CFOUTPUT> <H2>Today's date is #DateFormat(Now( ),'mm/dd/yyyy')#</H2> </CFOUTPUT> </BODY> </HTML>
<CFOUTPUT>) and two functions
(DateFormat( ) and Now( )) to
output the current date to the browser. We'll get to what this
tag and the functions do in a bit. For now, we're just
concerned with running the template and understanding how CFML and
HTML coexist
.
http://www.oreilly.com/catalog/coldfusion). You
should put the file in a directory accessible under the root
directory of your particular web server. For example, if the root
directory for your web server is
c:\inetpub\wwwroot, you can create a
subdirectory two levels down such as
c:\inetpub\wwwroot\examples\chapter2 and save
the template there as 2-1.cfm. Now if you use
your web browser to view this file
(http://127.0.0.1/examples/chapter2/2-1.cfm),
you'll see the web page displayed in Figure 2-1.
TRUE or FALSE. In numeric
operations, Boolean values evaluate to 1 for
TRUE and 0 for
FALSE. When dealing with strings, Boolean values
are set to Yes for TRUE and
No for FALSE. Note that no
quotes are necessary to delimit Boolean values.
"This is a string." and 'So
is this!' are both strings. "1000" and
'1000' are also strings so long as the numbers are
delimited by a set of quotes. The empty string can be written as
either '' or "". There are
certain special characters that must be escaped within strings. These
special characters are the single quote ('),
double quote ("), and pound sign
(#). These characters may be escaped by doubling
up on them as in the following
examples:
<CFSET String1 = "This is a ""good"" use of escaped double quotes"> <CFSET String2 = "This is a ''good'' use of escaped single quotes"> <CFSET String3 = "What is the ##1 team in the league?">
<CFSET> is a CFML tag you use to set a
variable to a particular value.
Test,
MyVariable, My_variable,
MyVariable1, and
MyDescriptive_var2 are all valid ColdFusion
variables, while 4C, My
Variable, Phone#, and
A/P aren't.
Time, Date, and
Order.
Application, Attribute,
Caller, CGI,
Client, Cookie,
Form, Variable,
Request, Server,
Session, URL, and
Query.
_date,
_eurodate, _float,
_integer, _range,
_required, or _time, as these
are reserved suffixes for server-side form validation variables and
can cause naming conflicts.
1, test,
MyVar, or CHR(54). Compound
expressions let you to evaluate data that is acted upon by operators.
For example, 1*10 is a mathematical expression
that evaluates to 10. The values
1 and 10 are both data, while
the asterisk (*) is considered an operator. On the
other end of the spectrum, expressions can be complex, consisting of
one or more subexpressions:
<CFSET x = 1+(10 MOD (3 * (11 - ACOS(-1))))>
<CFSET x =
10*(3+2)> uses the asterisk (*) as an
operator to multiply 10 by the sum of another expression that uses
the plus (+) operator to add 3 and 2. There are
four types of operators available in ColdFusion:
True/False.
&) concatenates strings.
True/False values.
|
Operator
|
Operation
|
Type
|
P
|
|---|---|---|---|
|
Unary +, unary -
|
Sign change
|
<CFOUTPUT> tag.
CFOUTPUT is a paired tag, which means that it has
both start and end tags. CFOUTPUT tells ColdFusion
to parse any text found between the tag pairs for variables and
expressions that need to be evaluated. We'll use the
CFOUTPUT tag in a variety of ways throughout the
book; it is one of the most commonly used CFML tag. For now,
let's focus on how the CFOUTPUT tag outputs
simple variable values.
CFSET tags and then outputs the values of the
variables within CFOUTPUT tags:
<!--- assign values to variables ---> <CFSET x = 1> <CFSET y = x+2> <CFSET Name = "Rob"> <CFSET z = Name> <CFSET Authenticated = True> <CFSET TheDate = DateFormat(Now( ),'mm/dd/yyyy')> <!--- output the variable values ---> <H2>Writing Output</H2> <CFOUTPUT> x = #x#<BR> y = #y#<BR> Name = #Name#<BR> z = #z#<BR> TheDate = #TheDate#<BR> Authenticated = #Authenticated#<BR> </CFOUTPUT>
#) in this example.
ColdFusion uses pound signs to separate expressions from literal
text. When ColdFusion encounters an expression surrounded by pound
signs, it attempts to evaluate it.
CFOUTPUT tags. Use pound signs around
variable names when you want to substitute the variable's value
within your output:
<CFOUTPUT> Hello #Name#, how are you today? </CFOUTPUT>
<CFOUTPUT> Hello #FirstName# #LastName#, how are you today? </CFOUTPUT>
<CFOUTPUT> The absolute value of -1 is #ABS(-1)#. </CFOUTPUT>
<CFIF>, <CFELSEIF>,
and <CFELSE> tags, a C-style switch
statement with the <CFSWITCH>,
<CFCASE>, and
<CFDEFAULTCASE> tags, and the IIF(
) function for inline conditionals.
<CFIF expression> HTML and CFML... <CFELSEIF expression> HTML and CFML... <CFELSE> HTML and CFML... </CFIF>
CFIF statement can evaluate any expression
capable of returning a Boolean value. If the statement evaluates
True, ColdFusion processes the code associated
with the CFIF statement. The
CFELSEIF statement provides an alternate
expression in the event that the expression in the
CFIF statement evaluates False.
Any number of CFELSEIF statements can provide
additional decision-making options. The CFELSE
statement provides a default option in the event that both the
CFIF statement and any CFELSEIF
statements all evaluate False. The following
example uses if/elseif/else logic to evaluate a URL variable called
Action:
<CFIF URL.Action IS "Add"> <CFINCLUDE TEMPLATE="AddRecord.cfm"> <CFELSEIF URL.Action IS "Edit"> <CFINCLUDE TEMPLATE="EditRecord.cfm"> <CFELSEIF URL.Action IS "Delete"> <CFINCLUDE TEMPLATE="DeleteRecord.cfm"> <CFELSE> You have chosen an invalid action! </CFIF>
Action, one of three
additional templates is called via a
<CFINCLUDE> tag (which we'll discuss
shortly). If the value of the URL variable doesn't match one of
the values in the CFIF or
CFELSEIF statements, a default message contained
within the CFELSE tag is displayed.
<CFLOOP> tag, including index
(for) loops, conditional
(while) loops, collection loops, list loops, and
query loops. For now, we are just going to cover basic index and
conditional loops. Query loops are covered in Chapter 4, while collection and list loops are covered
in Chapter 6.
for loop,
an index loop repeats a number of times specified as a range of
values:
<CFLOOP INDEX="index_name" FROM="number" TO="number" STEP="increment"> HTML and CFML... </CFLOOP>
INDEX attribute of
the loop specifies a variable name to hold the value corresponding to
the current iteration of the loop. The FROM
attribute initializes the starting value for the loop. The
TO attribute refers to the value at which
iteration should stop. STEP specifies the
increment value for each iteration of the loop.
STEP may be either a positive or a negative
number. Here is an example that uses an index loop to output all the
numbers between 10 and 100 in
increments of 10, with each number on its own
line:
<H2>Calling the loop...</H2>
<CFLOOP INDEX="i"
FROM="10"
TO="100"
STEP="10">
<CFOUTPUT>
#i#<BR>
</CFOUTPUT>
</CFLOOP>
<H2>We are now outside of the loop</H2>INDEX is set to i. Since
we want to begin the count at 10, we assign that
value to the FROM attribute. The
TO attribute is set to 100
because that is where we want the loop to stop iterating. In order to
get the loop to increment by multiples of 10, the
STEP attribute is set to 10.
Executing the template results in the output shown in Figure 2-4.
<CFINCLUDE> tag.
CFINCLUDE is the ColdFusion equivalent of Server
Side Includes (SSI). CFINCLUDE takes a single
attribute, TEMPLATE, which specifies a logical
path to the file to be included. The logical path must be either a
virtual directory or a directory that has been explicitly mapped in
the ColdFusion Administrator:
<CFINCLUDE TEMPLATE="MyIncludedFile.cfm">
<CFINCLUDE TEMPLATE="/MyDirectory/MyIncludedFile.txt">
<!--- set the title for the page ---> <CFSET Title="My Page"> <!--- include the header for the page ---> <CFINCLUDE TEMPLATE="_header.cfm"> <H2>Hello World!</H2> I'm just some regular text. <!--- include the footer ---> <CFINCLUDE TEMPLATE="_footer.cfm">
Title. Next, a template called
_Header.cfm is included using the
CFINCLUDE tag. I use the underscore as the first
character of any include files so that I can differentiate include
files from other templates. The next part of the template constitutes
the body of the page. In this example, we just output some simple
text. The last line of code in the template uses another
filename.cfm?param1=value1¶m2=value2¶m3=value3
filename.cfm?param1=value1¶m2=value2¶m3=value3
<!--- set variables to be passed to another template ---> <CFSET x=1> <CFSET color="green"> <CFSET Pass = True> <H2>Passing Data via URL Parameters</H2> <!--- Create a hyperlink containing URL parameters ---> <CFOUTPUT> <AHREF="ReceiveURLParameters.cfm?x=#x#&color=#color#&pass=#pass#">Clickthis link to pass the URL parameters</A> </CFOUTPUT>
ReceiveURLParameters.cfm?x=1&color=green&Pass=True
ACTION attribute of the
FORM tag. Within the receiving template, each form
field can be referenced by prefixing the field name with
Form, as in
Form.
MyField. To see
just how this works, let's look at an example. The
ContactForm.cfm template, shown in Example 3-6, creates a simple HTML form that collects
basic contact information and posts it to the
DisplayContactInfo.cfm template, shown in Example 3-7.
<HTML>
<HEAD>
<TITLE>Passing Variables via Form Fields</TITLE>
</HEAD>
<BODY>
<H2>Employee Contact Information</H2>
<FORM ACTION="DisplayContactInfo.cfm" METHOD="post">
<TABLE>
<TR>
<TD>Name:</TD>
<TD><INPUT TYPE="text" NAME="Name" SIZE="25" MAXLENGTH="50"></TD>
</TR>
<TR>
<TD>Title:</TD>
<TD><INPUT TYPE="text" NAME="Title" SIZE="25" MAXLENGTH="50"></TD>
</TR>
<TR>
<TD>Department:</TD>
<TD><INPUT TYPE="text" NAME="Department" SIZE="25" MAXLENGTH="50"></TD>
</TR>
<TR>
<TD>E-mail:</TD>
<TD><INPUT TYPE="text" NAME="Email" SIZE="25" MAXLENGTH="255"></TD>
</TR>
<TR>
<TD>Phone Ext.:</TD>
<TD><INPUT TYPE="text" NAME="PhoneExt" SIZE="6" MAXLENGTH="4"></TD>
</TR>
<TR>
<TD COLSPAN="2"><INPUT TYPE="submit" NAME="Submit" VALUE="submit"></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
Name: #Form.Name# Title: #Form.Title# Department: #Form.Name# E-mail: #Form.Email# Phone Ext.: #Form.PhoneExt#
CFPARAM tag to assign a default value to
any parameters expected by your application template. That way, if an
expected parameter isn't passed, a default value is
automatically assigned, and the application can continue processing.
If you remember, the CFPARAM tag was covered
earlier in Chapter 2. Additional information on
the CFPARAM tag can be found in Appendix A.
CFPARAM tag is
great for assigning a default value if one doesn't exist,
however, it doesn't allow you to display an error message or
perform an alternate action if an expected variable doesn't
exist. The next method uses the IsDefined( )
function to check for the existence of a variable before allowing
processing of the template to continue. If the expected variable
exists, the template is processed. If not, an error message is
written to the browser. For example, if you have a template that is
expecting a URL parameter named ArticleID to be
passed in, you can use the following code to output an error message
if the parameter isn't present:
<!--- if the parameter is present, output it to the screen --->
<CFIF IsDefined('URL.ArticleID')>
<CFOUTPUT>
The article ID is: #URL.ArticleID#
</CFOUTPUT>
Additional program code...
<!--- otherwise, output an error message --->
<CFELSE>
A required parameter, <B>ArticleID</B> was not supplied!
</CFIF>IsDefined( ) function checks
for the existence of a URL parameter called
ArticleID. If it is present, its value is output
to the browser and any additional program code for the page is
executed. If the parameter isn't present, an error message to
that effect is written to the browser.
CFQUERY tag is the main tag used by ColdFusion to
interact with databases. Using CFQUERY, you can
pass any Structured Query Language (SQL) statement to a data source
registered with the ColdFusion Administrator. The content of your SQL
statements determines what action is performed against the data
source. The next section provides a quick primer on SQL.
CFQUERY tag works by establishing a connection
with the specified data source, passing a series of SQL commands, and
returning query variables that contain information about the
operation. The basic syntax for using the CFQUERY
tag is as follows:
<CFQUERY NAME="query_name"
DATASOURCE="datasource_name"
DBTYPE="dbtype"
CONNECTSTRING="connection_string">
SQL statements
</CFQUERY>CFQUERY tag specifies information about the data
source and how ColdFusion should access it. The
NAME attribute assigns a name to the query. Valid
query names must begin with a letter and can contain only letters,
numbers, and underscore characters. NAME is
required when passing an SQL SELECT statement and
is optional for all other SQL operations.
The DATASOURCE attribute is required in all
circumstances except when DBTYPE is
Query or Dynamic and specifies
the name of the data source (as it appears in the ColdFusion
Administrator) to connect to when executing the query. The
DBTYPE attribute is optional and specifies the
type of database driver to use when connecting to the data source.
Possible entries are:
ODBC (the default)OLEDB
Oracle73
Oracle80
CFQUERY
tag. If you don't completely understand everything we are about
to cover, don't worry. Every aspect (and more) of the SQL we
cover in the primer is covered in more detail throughout this and the
next chapter.
SELECT,
INSERT, UPDATE, and
DELETE, respectively:
SELECT
INSERT
UPDATE
DELETE
FROM
ProgrammingCF that
contains several database tables including one called
EmployeeDirectory. The schema and sample data for
this database are listed in Appendix C. For
simplicity, I've chosen to use a Microsoft Access database for
all the examples; you can download the sample Access database from
O'Reilly's catalog page for this book (http://www.oreilly.com/catalog/coldfusion/).
Of course, you can use any database you choose. To get started, you
need to create a new database and save it as
ProgrammingCF. Next, create a new table and add
the fields shown in Table 4-2.
|
Field Name
|
Field Type
|
Max Length
|
|---|---|---|
|
ID (primary key)
|
AutoNumber
|
N/A
|
|
Name
|
Text
|
255
|
|
Title
|
Text
|
255
|
|
Department
|
SELECT statement to retrieve
records from a database, those records are returned in the order in
which they were originally entered. If you want to change the order
in which the records are displayed, you need to use an ORDER
BY clause, as shown in Example 4-2.
<CFQUERY NAME="GetEmployeeInfo" DATASOURCE="ProgrammingCF">
SELECT Name, Title, Department, Email, PhoneExt
FROM EmployeeDirectory
ORDER BY Name ASC
</CFQUERY>
<TABLE CELLPADDING="3" CELLSPACING="0">
<TR BGCOLOR="#888888">
<TH>Name</TH>
<TH>Title</TH>
<TH>Department</TH>
<TH>E-mail</TH>
<TH>Phone Extension</TH>
</TR>
<CFOUTPUT QUERY="GetEmployeeInfo">
<TR BGCOLOR="##C0C0C0">
<TD>#Name#</TD>
<TD>#Title#</TD>
<TD>#Department#</TD>
<TD><A HREF="Mailto:#Email#">#Email#</A></TD>
<TD>#PhoneExt#</TD>
</TR>
</CFOUTPUT>
</TABLE>ORDER BY clause specifies which column or
columns to use in ordering the query results. Sorting can be either
ASC (ascending) or DESC
(descending). Example 4-2 sorts the result set by
NAME column, in ascending order. The output is
shown in Figure 4-1.
ORDER
BY clause as in:
<CFQUERY NAME="GetEmployeeInfo" DATASOURCE="ProgrammingCF">
SELECT Name, Title, Department, Email, PhoneExt
FROM EmployeeDirectory
ORDER BY Title ASC, Name ASC
</CFQUERY>CFOUTPUT tag
has an attribute called GROUP that lets you to
group output from your record sets before displaying it to the
browser. There are two ways to use the GROUP
attribute of the CFOUTPUT tag. The first method
uses GROUP to remove any duplicate rows from the
query result set. This is useful in
situations where the result set you return from a query contains
duplicate rows of data but you want to display only unique records.
GROUP attribute of the
CFOUTPUT tag.
<CFQUERY NAME="GetDepartment" DATASOURCE="ProgrammingCF">
SELECT Department
FROM EmployeeDirectory
ORDER BY Department
</CFQUERY>
<HTML>
<HEAD>
<TITLE>Using GROUP to remove duplicate records</TITLE>
</HEAD>
<BODY>
<H2>Departments:</H2>
<CFOUTPUT QUERY="GetDepartment">
#Department#<BR>
</CFOUTPUT>
</BODY>
</HTML>
CFOUTPUT tag to read like this:
<CFOUTPUT QUERY="GetDepartment" GROUP="Department" GROUPCASESENSITIVE="No">
GROUP="Department" to the
CFOUTPUT tag tells ColdFusion to discard any
duplicate values in the result set and output only unique values. The
GROUPCASESENSITIVE attribute indicates whether
grouping should be case-insensitive or case-sensitive. This attribute
is optional and defaults to Yes. For our example,
set GROUPCASESENSITIVE to No in
case someone enters the name of a department using the wrong case.
The difference in output is shown in Figure 4-3.
CFLOOP tag
with the QUERY attribute) performs essentially the
same job as using a CFOUTPUT tag with the
QUERY attribute. A query loop iterates over each
row in a query object. Optionally, a start row and end row within the
query may be specified:
<CFLOOP QUERY="query_name"
STARTROW="row_number"
ENDROW="row_number">
...
</CFLOOP>QUERY attribute
specifies the name of a valid ColdFusion query object.
STARTROW is optional and may be used to specify
the row within the query object where the loop should begin.
ENDROW is also optional and specifies the last row
within a query object that should be included within the loop.
QUERY
attribute of the CFOUTPUT tag to display the
contents of a query:
<CFQUERY NAME="GetEmployeeInfo" DATASOURCE="ProgrammingCF">
SELECT Name, Title
FROM EmployeeDirectory
</CFQUERY>
<CFLOOP QUERY="GetEmployeeInfo">
<CFOUTPUT>#Name#, #Title#<BR></CFOUTPUT>
</CFLOOP>CFOUTPUT tag such as the inability to nest
additional output queries within a CFOUTPUT block.
For example, the following code produces an error in ColdFusion
because you can't nest CFOUTPUT tags without
using the GROUP attribute:
<CFQUERY NAME="MyQuery1" DATASOURCE="MyDSN">
SELECT *
FROM MyTable
WHERE Field = Value
</CFQUERY>
<CFOUTPUT QUERY="MyQuery1">
<CFQUERY NAME="MyQuery2" DATASOURCE="MyDSN">
SELECT *
FROM MyTable
WHERE Field = Value
</CFQUERY>
<CFOUTPUT QUERY="MyQuery2">
Additional processing and output code here...
</CFOUTPUT>
</CFOUTPUT>CFOUTPUT block:
<CFQUERY NAME="MyQuery1" DATASOURCE="MyDSN">
SELECT *
FROM MyTable
WHERE Field = Value
</CFQUERY>
<CFOUTPUT QUERY="MyQuery1">
<CFQUERY NAME="MyQuery2" DATASOURCE="MyDSN">
SELECT *
FROM MyTable
WHERE Field = Value
</CFQUERY>
<CFLOOP QUERY="MyQuery2">
Additional processing and output code here...
</CFLOOP>
</CFOUTPUT>ParagraphFormat( ), Ucase( ),
Lcase( ),