+ All Categories
Home > Documents > Mastering ColdFusion 5

Mastering ColdFusion 5

Date post: 08-Dec-2016
Category:
Upload: raymond-camden
View: 239 times
Download: 5 times
Share this document with a friend
1214
MASTERING COLDFUSION ® 5 Arman Danesh Kristin Aileen Motlagh Raymond Camden San Francisco • Paris • Düsseldorf • Soest • London
Transcript
  • MASTERING COLDFUSION 5

    Arman DaneshKristin Aileen Motlagh

    Raymond Camden

    San Francisco Paris Dsseldorf Soest London

    2979fm.qxd 7/9/01 6:11 PM Page iii

  • Associate Publisher: Richard MillsAcquistion Editors: Diane Lowery, Tom CirtinDevelopmental Editor: Tom CirtinProduction Editor: Jennifer CampbellEditor: Kim WimpsettTechnical Editor: Guy RishElectronic Publishing Specialist: Maureen Forys, Happenstance Type-O-RamaProofreaders: Nelson Kim, Laurie OConnell, Yariv Rabinovitch, Nancy Riddiough, Amey GarberIndexer: Nancy GuentherCD Coordinator: Christine HarrisCD Technician: Kevin C. LyBook Designer: Robin Kibby, Kibbymega.comCover Designer: Design SiteCover Illustrator/Photographer: Sergie Loobkoff

    Copyright 2001 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. [(for books with reusable codeon the CD) The author(s) created reusable code in this publication expressly for reuse by readers. Sybex grants readers limited permissionto reuse the code found in this publication or its accompanying CD-ROM so long as (author(s)) are attributed in any application containingthe reusabe code and the code itself is never distributed, posted online by electronic transmission, sold, or commercially exploited as astand-alone product. Aside from this specific exception concerning reusable code,] No part of this publication may be stored in a retrievalsystem, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or other record, without theprior agreement and written permission of the publisher.

    Library of Congress Card Number: 2001090459

    ISBN: 0-7821-2979-X

    SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc. in the United States and/or other countries.Mastering is a trademark of SYBEX Inc.

    Screen reproductions produced with FullShot 99. FullShot 99 1991-1999 Inbit Incorporated. All rights reserved.FullShot is a trademark of Inbit Incorporated.

    The CD interface was created using Macromedia Director, COPYRIGHT 1994, 1997-1999 Macromedia Inc. For more information onMacromedia and Macromedia Director, visit http://www.macromedia.com.

    Netscape Communications, the Netscape Communications logo, Netscape, and Netscape Navigator are trademarks of Netscape Commu-nications Corporation.Netscape Communications Corporation has not authorized, sponsored, endorsed, or approved this publication and is not responsible for itscontent. Netscape and the Netscape Communications Corporate Logos are trademarks and trade names of Netscape CommunicationsCorporation. All other product names and/or logos are trademarks of their respective owners.Internet screen shot(s) using Microsoft Internet Explorer 5 reprinted by permission from Microsoft Corporation.

    TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by followingthe capitalization style used by the manufacturer.

    The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software wheneverpossible. Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s). The author and the pub-lisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept noliability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damagesof any kind caused or alleged to be caused directly or indirectly from this book.

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    2979fm.qxd 7/9/01 6:11 PM Page iv

  • Software License Agreement: Terms and ConditionsThe media and/or any online materials accompanying this bookthat are available now or in the future contain programs and/ortext files (the Software) to be used in connection with the book.SYBEX hereby grants to you a license to use the Software, subjectto the terms that follow. Your purchase, acceptance, or use of theSoftware will constitute your acceptance of such terms.

    The Software compilation is the property of SYBEX unless other-wise indicated and is protected by copyright to SYBEX or othercopyright owner(s) as indicated in the media files (the Owner(s)).You are hereby granted a single-user license to use the Softwarefor your personal, noncommercial use only. You may not repro-duce, sell, distribute, publish, circulate, or commercially exploitthe Software, or any portion thereof, without the written consentof SYBEX and the specific copyright owner(s) of any componentsoftware included on this media.

    In the event that the Software or components include specificlicense requirements or end-user agreements, statements of condi-tion, disclaimers, limitations or warranties (End-User License),those End-User Licenses supersede the terms and conditionsherein as to that particular Software component. Your purchase,acceptance, or use of the Software will constitute your acceptanceof such End-User Licenses.

    By purchase, use or acceptance of the Software you further agreeto comply with all export laws and regulations of the United Statesas such laws and regulations may exist from time to time.

    Reusable Code in This BookThe authors created reusable code in this publication expressly forreuse for readers. Sybex grants readers permission to reuse for anypurpose the code found in this publication or its accompanyingCD-ROM so long as all of the authors are attributed in any appli-cation containing the reusable code, and the code itself is neversold or commercially exploited as a stand-alone product.

    Software SupportComponents of the supplemental Software and any offers associ-ated with them may be supported by the specific Owner(s) of thatmaterial but they are not supported by SYBEX. Informationregarding any available support may be obtained from theOwner(s) using the information provided in the appropriateread.me files or listed elsewhere on the media.

    Should the manufacturer(s) or other Owner(s) cease to offer sup-port or decline to honor any offer, SYBEX bears no responsibility.This notice concerning support for the Software is provided foryour information only. SYBEX is not the agent or principal of theOwner(s), and SYBEX is in no way responsible for providing anysupport for the Software, nor is it liable or responsible for any sup-port provided, or not provided, by the Owner(s).

    WarrantySYBEX warrants the enclosed media to be free of physical defectsfor a period of ninety (90) days after purchase. The Software is not

    available from SYBEX in any other form or media than thatenclosed herein or posted to www.sybex.com. If you discover adefect in the media during this warranty period, you may obtain areplacement of identical format at no charge by sending the defec-tive media, postage prepaid, with proof of purchase to:

    SYBEX Inc.Customer Service Department1151 Marina Village ParkwayAlameda, CA 94501(510) 523-8233Fax: (510) 523-2373e-mail: [email protected]: HTTP://WWW.SYBEX.COM

    After the 90-day period, you can obtain replacement media ofidentical format by sending us the defective disk, proof of pur-chase, and a check or money order for $10, payable to SYBEX.

    DisclaimerSYBEX makes no warranty or representation, either expressed or implied, with respect to the Software or its contents, quality,performance, merchantability, or fitness for a particular purpose.In no event will SYBEX, its distributors, or dealers be liable to you or any other party for direct, indirect, special, incidental, consequential, or other damages arising out of the use of or inability to use the Software or its contents even if advised ofthe possibility of such damage. In the event that the Softwareincludes an online update feature, SYBEX further disclaims anyobligation to provide this feature for any specific duration otherthan the initial posting.

    The exclusion of implied warranties is not permitted by somestates. Therefore, the above exclusion may not apply to you.This warranty provides you with specific legal rights; there maybe other rights that you may have that vary from state to state.The pricing of the book with the Software by SYBEX reflects theallocation of risk and limitations on liability contained in thisagreement of Terms and Conditions.

    Shareware DistributionThis Software may contain various programs that are distributedas shareware. Copyright laws apply to both shareware and ordi-nary commercial software, and the copyright Owner(s) retains allrights. If you try a shareware program and continue using it, youare expected to register it. Individual programs differ on details oftrial periods, registration, and payment. Please observe therequirements stated in appropriate files.

    Copy ProtectionThe Software in whole or in part may or may not be copy-protectedor encrypted. However, in all cases, reselling or redistributing thesefiles without authorization is expressly forbidden except as specifi-cally provided for by the Owner(s) therein.

    2979fm.qxd 7/9/01 6:11 PM Page v

  • To Mrs. G: thanks for all those samosas.Arman Danesh

    To The Boojie.Kristin Motlagh

    For Jacob.Raymond Camden

    2979fm.qxd 7/9/01 6:11 PM Page vii

  • ACKNOWLEDGMENTS

    Even though the task of writing such long treatises now seems almost routine, it can nevermask the enormous contributions of so many people in bringing projects such as these toreality.

    First, I must thank the entire team brought together to make this book a reality. Notably, Iam grateful to my coauthors, Kristin Motlagh and Raymond Camden; our team of projectmanagers and editors at Sybex including Richard Mills, Tom Cirtin, Jennifer Campbell, andKim Wimpsett; and the nameless many who helped in the task of producing this book.

    Finally, my wife deserves credit for tolerating that I was always in front of the computerscreen throughout the writing of this book even while she traversed through the firsttrimester of pregnancy without my full support and assistance.

    Arman Danesh

    The following people and groups have provided much-appreciated kindness and assistanceduring the writing of this book: Michael Dinowitz, Michael Imhoff, Emily Kim, AnnetteKunovic, Abraham Lloyd, Angelo McComis, Dave Medinets, Michael Smith, Dan Switzer,Nate Weiss, the CFGURU mailing list, and the Ohio Area CFUG.

    I would like to thank our development editor Tom Cirtin and our associate publisherRichard Mills; their dedication to the book and the ColdFusion line at Sybex is highly com-mendable. Also, thanks to production editor Jennifer Campbell and editor Kim Wimpsett,who provided invaluable feedback about each chapter and did an excellent editing job. GuyRish also deserves great recognition for his work as the sole technical editor for the book.

    I would again like to thank Arman for this great opportunity. This book would not exist orbe as good as it is without him. And I would like to thank Raymond Camden who has addedenormous value to this book with his knowledge of many advanced ColdFusion topics.

    Finally, thanks go to the two men at the center of my life: Safa and Reyhan.

    Kristin Motlagh

    2979fm.qxd 7/9/01 6:11 PM Page viii

  • Id like to thank my friends and co-workers at Macromedia who put up with my incessantquestions about various new features, specifically Tim Buntel, John Peyton, Dave Gruber,and others. Along with Kristin and Arman, I want to thank the staff at Sybex for letting meparticipate in this project. Tom Cirtin and Richard Mills provided great leadership andencouragement. The editing by Jennifer Cambell, Kim Wimpsett, and Guy Rish was excel-lent and helped make this book what it is today. I would like to thank Arman and Kristin aswell. It was great working with you, both on this book and the previous editions.

    Lastly, Id like to thank my wife, Jeanne, for her support and understanding while I workedlate nights writing.

    Raymond Camden

    2979fm.qxd 7/9/01 6:11 PM Page ix

  • ABOUT THE AUTHORS

    Arman Danesh is pursuing an advanced degree in computer science at Simon Fraser Uni-versity in Vancouver. He also serves as the technical manager for The Bah World (http://www.bahai.org), the official Web site of the Bah International Community, and BahWorld News Service (http://www.bahaiworldnews.org), a ColdFusion-driven online newsservice. Additionally, he is the editorial director for Juxta Publishing Limited (http://www.juxta.com). He has been working with ColdFusion since 1997 and maintains several ColdFusion-based Web sites. Arman has written more than a dozen books including Mas-tering Linux, Making Linux Work: Essential Tips and Techniques, Safe and Secure: Secure YourHome Network and Protect Your Privacy Online, and Teach Yourself JavaScript in a Week.

    Kristin Aileen Motlagh has extensive experience working with ColdFusion. She has man-aged and developed interactive ColdFusion-based applications for companies such as MCI,NASDAQ, GE, and the World Bank. Most recently, Kristin helped co-found Trilemetry(http://www.trilemetry.com), a Web sitedevelopment company. She has also worked on adigital restoration project for the Bah World Centre (http://www.bahai.org), served as amember of Team Allaire, taught a ColdFusion course through the HTML Writers Guild,and coauthored both Mastering ColdFusion 4 and Mastering ColdFusion 4.5. Additionally,Kristin has spoken at a variety of conferences and user groups. You can now find Kristin athome learning the fine points of raising a healthy two-year-old boy by day and catching upon old Babylon 5 episodes by night.

    Raymond Camden has worked with ColdFusion for many years. During this time, he hasdeveloped applications for clients such as Bank of America, Netscape, Allaire, and Voice ofAmerica. Raymond was a member of Team Allaire until joining Allaire, now Macromedia, inthe fall of 2000. Raymond now works as the compliance engineer for Macromedia Spectra.He was a contributing author to Mastering ColdFusion 4 and Mastering ColdFusion 4.5 as wellas a coauthor for Allaire Spectra e-Business Construction Kit. He has written numerous articlesfor the Allaire Developer Zone as well as the ColdFusion Developers Journal. Raymond is anabsolute Star Wars fanatic and listens to techno music (which bugs the heck out of everyonearound him).

    2979fm.qxd 7/9/01 6:11 PM Page x

  • FOREWORD

    M astering ColdFusion 5 is a great book for anyone who wants to move from creating staticHTML pages to creating dynamic, interactive Web sites using one of the most popular Webdevelopment languages on the market. This book takes your HTML knowledge and buildson it step by step to help you create almost any type of Web applicationfrom a companyintranet to an advanced e-commerce site. Throughout its thorough coverage, the books styleis always engaging and never intimidating.

    Starting out, Mastering ColdFusion 5 guides you through programming concepts such asvariables, functions, expressions, and flow control. After youve mastered the basics of work-ing with dynamic information on your pages, you learn how to use databases with your Websites, a concept that has changed the way people use the Web. Storing your data in a databaselets you create applications that give your users access to large amounts of information whileonly displaying exactly the information they need. To make the most of your database-drivenapplications, Mastering ColdFusion 5 steps you through designing a relational database andusing basic and advanced query and output techniques.

    As many organizations begin to move many of their current business processes to Web-basedapplications, it is important that Web developers understand how to integrate their applicationswith existing systems and other technologies. Mastering ColdFusion 5 teaches you to use Cold-Fusions powerful features to do just that; youll learn how to include Java and COM modules,call mail systems, use HTTP and FTP, and incorporate LDAP servers into your application.

    Finally, Mastering ColdFusion 5 introduces many of the advanced concepts that allow Cold-Fusion developers to write robust, full-featured Web applications. It explains how to set upapplication security, implement a search engine, use XML, and write dynamic expressions inthe same easy-to-understand style that it describes basic concepts. The book is especiallyadept at explaining the important new features of ColdFusion 5, such as queries of queries,user-defined functions, and certain server administration features.

    For anyone just starting out with ColdFusion, Mastering ColdFusion 5 is a wonderful way tobegin; for those who have experimented with ColdFusion, this book will help you take yourprogramming abilities to a new level; and for experienced ColdFusion developers, this bookis a great introduction to the powerful new features of ColdFusion 5.

    Libby FrelighSenior Product Manager, MacromediaJune 2001

    2979fm.qxd 7/9/01 6:11 PM Page xxiii

  • INTRODUCTION

    This book is designed to teach you how to develop sophisticated, dynamic, and interactiveWeb sites by using ColdFusion.

    ColdFusion, launched in 1995 by Allaire Corporation (now owned by Macromedia), wasthe first Web application server available for Windows NTbased Web servers. ColdFusionis now at version 5, which is the version covered in this book.

    Today, ColdFusion is used by half of all Fortune 500 companies by some counts. It hasgrown from its modest beginnings to this wide level of industry acceptance because it offers a powerful yet easy-to-use environment in which Web-based applications can be rapidlydesigned, prototyped, and deployed. ColdFusion is available for Windows NT, HPUX,and Linux.

    Compared to some other Web application server products, ColdFusion offers a simplicitythat often belies its powerful capabilities. These capabilities include working with data indatabases; interacting with the Internet through FTP, e-mail, and HTTP; and much more.

    The goal of this book is to teach Web developers how to turn their knowledge of HTMLinto a strong command of ColdFusion so that they can begin to develop the dynamic Webapplications and interactive Web sites that are becoming common on the Internet andintranets worldwide.

    The Components of ColdFusionColdFusion consists of several components that, when put together, create the powerfuldevelopment and deployment environment for Web applications. These components are:

    ColdFusion Markup Language

    ColdFusion Application Server

    ColdFusion Studio

    ColdFusion Administrator

    ColdFusion Markup LanguageLearning to develop applications in ColdFusion is centered around learning the ColdFusionMarkup Language (CFML).

    2979fm.qxd 7/9/01 6:11 PM Page xxv

  • xxvi

    The name of the language offers insight as to its nature. In terms of style and use, CFMLis a close relative to the Hypertext Markup Language (HTML). Like HTML, it is tag basedand doesnt require learning a programming language with a unique syntax in the way thatJavaScript or VBScript do. However, the similarities end there: HTML is used to define thestructure and, to some extent, the layout and design of a Web page. CFML is used to specifyactions to take in the form of small server-based programs. As in most Web application envi-ronments, HTML and CFML are used in files processed by the ColdFusion server to gener-ate complete Web pages to be displayed in users browsers.

    Application ServerThe process of taking files containing CFML and HTML and converting them into com-pleted Web pages for delivery to the users browser is handled by the ColdFusion ApplicationServer. The application server is an extension of the Web server that handles the processingof all files containing CFML tags and returning to the Web server pure HTML files fordelivery to the user.

    The ColdFusion Application Server offers numerous features that make developing anddeploying reliable, robust, and high-performance Web applications and interactive Web sitespossible. These include:

    Scalability features such as the capability to track client state, load balancing, andclustering.

    Open integration including support for the emerging Extensible Markup Language(XML) standard, built-in support for high-end database servers such as Oracle andSybase, support for popular application development standards such as the CommonObject Request Broker Architecture (CORBA), and the ability to extend the serverscapabilities by using standard programming languages such as Visual C++.

    Security features include a comprehensive authentication system, remote developmentwith security to allow secure control over Web site content from remote locations, andintegration with Windows NT security and authentication systems.

    StudioColdFusion Studio is an integrated development environment (IDE) for ColdFusion. IDEsgenerally offer a complete graphical environment in which to develop applications.

    Studio is optimized for development of ColdFusion-based Web sites and applications(although it can be used to develop static Web sites that dont use any of the interactive or

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxvi

  • xxvii

    dynamic features of ColdFusion). Among the features of Studio that make it a valuable tool forColdFusion development are:

    Access to the ColdFusion documentation and Help You can access complete referenceinformation while you are developing.

    Tag editors You can build complete tags by filling in simple-to-follow forms.

    Project management You can group files into sets of related files known as projects.These projects can be managed as single entities, which allows for global tasks such assearch-and-replace across whole projects.

    Code snippets You can create a library of code blocks (called snippets) that you commonlyuse and then quickly include them in the files you are creating.

    Expression Builder ColdFusion allows the creation of some fairly complex expressions.This is simplified in Studio through a point-and-click expression-building applet.

    Visual database tools One of the powers of ColdFusion is that it makes accessing datastored in relational databases quite easy. You can use visual tools to create database queries,making the creation of code for accessing databases a trivial matter.

    Validation tools You can ensure that the code you have developed is valid through linkvalidation and CFML and HTML code validation capabilities.

    Code debugging ColdFusion application development is a form of programming, and likeall forms of programming, it is impossible to write 100-percent accurate code all the time.You can use debugging tools to help pinpoint bugs and errors in code, saving time andfrustration.

    Design layout and page preview You can design your pages by using visual page designtools and can preview them inside an integrated browser.

    You can find a basic introduction to using Studio as a development tool in Chapter 22,Using ColdFusion Studio.

    ColdFusion AdministratorThe ColdFusion Administrator is an application that enables you to manage your Cold-Fusion Application Server through a simple, forms-driven Web interface.

    With the ColdFusion Administrator, you can configure all aspects of your servers opera-tion, including setting performance-related options, managing security settings, creatingdatabase connections, indexing content, and much more. The ColdFusion Administrator iscovered in Chapter 39, The ColdFusion Administrator.

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxvii

  • xxviii

    How Does ColdFusion Work?ColdFusion integrates tightly with the Web server with which it is installed. This allows for a quick and easy transfer of data between the Web server and the ColdFusion ApplicationServer.

    This tight integration is normally achieved through the Web servers application program-ming interface (API). The API provides a way for an external product such ColdFusion tobecome an integral part of the operating environment of the Web server. All major Webservers including Apache, Netscape Enterprise Server, and Microsoft Internet InformationServer offer APIs, and ColdFusion is designed to work with all of these.

    By using the API to connect with the Web server, several benefits are automaticallyachieved:

    The ColdFusion server essentially becomes part of the Web server.

    A separate program is not launched each time a dynamic page is requested; instead, thepages are interpreted by the ColdFusion server and returned to the user while the Cold-Fusion server remains loaded and in memory as long as the Web server is running.

    Tight integration with the security and authentication model used by the Web server ispossible.

    For more insight into the way in which ColdFusion interacts with the Web server, refer toAppendix D, Differences between ColdFusion and Traditional Server-Side Programming.

    RequirementsTo use ColdFusion in your environment, you need to meet certain hardware and softwarerequirements. Using ColdFusion effectively also requires previous experience in certain areasof Web development. These requirements are outlined in the following sections.

    HardwareThe ColdFusion Application Server for Windows has the following minimum hardwarerequirements, according to Macromedia:

    Pentium or higher running Windows 95, 98, NT, or 2000

    350MB of disk space

    256MB of RAM

    A CD drive

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxviii

  • xxix

    Of course, the real hardware requirements will depend largely on your individual needs.For instance, if you are running ColdFusion on your own workstation for development pur-poses, you will need far less resources than running it on a heavily used production server.

    As a general rule of thumb, the system on which you plan to run ColdFusion should alreadybe running a Web server quite comfortably under the expected user load. If you already findthat your Web server cant handle the number of hits you receive, then you cant expect Cold-Fusion to perform adequately either.

    NOTE For hardware requirements on Linux, please refer to Chapter 41, ColdFusion for Linux.

    Macromedia has a different set of hardware requirements for ColdFusion Studio:

    Windows 95, 98, NT, or 2000 (Studio is not available for Unix or Linux)

    35MB of disk space

    64MB of RAM

    The ColdFusion Administrator has no special requirements; it is simply a ColdFusionapplication that runs on top of the ColdFusion Application Server. If you have sufficienthardware resources to run the Application Server, then the Administrator will operate with-out difficulty.

    SoftwareTo run the ColdFusion Application Server, you need to meet two software requirements:

    The TCP/IP networking protocol must be enabled on the system.

    A suitable Web server must be running.

    Table I.1 describes some suitable Web servers.

    TABLE I.1: Web Servers for Use with ColdFusion

    Web Server Platform Free? For More Information

    Apache Unix, Linux, Windows NT Yes http://www.apache.org

    Windows NT Yes http://www.microsoft.com/iis

    Netscape Enterprise Server Unix, Windows NT No http://www.netscape.com

    OReilly WebSite Pro Windows NT, 98, 95 No http://website.ora.com

    Yes http://www.microsoft.comWindows NT Worksta-tion, Windows 98, or 95

    Microsoft PersonalWeb Server

    Microsoft Internet Infor-mation Server

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxix

  • xxx

    ExperienceColdFusion is an environment for developing Web applications. As such, it is impossible touse ColdFusion effectively without first having a firm grasp of HTML, including advancedfeatures such as tables and forms.

    Without this knowledge, you cannot develop usable applications with ColdFusion.Accordingly, you should have a good grasp of HTML. If you need to review HTML, con-sider reading Mastering HTML 4, Second Edition, by Deborah S. Ray and Eric J. Ray orHTML Complete, both from Sybex.

    In addition to having a firm grounding in HTML, at least a basic knowledge of JavaScript isuseful. Since its introduction in Netscape Navigator 2, JavaScript has quickly become the stan-dard scripting language for client-side scripting and is commonly used on Internet and intranetsites. Because JavaScript can be used to perform so many useful functions on Web pages and inWeb applications, having some knowledge of JavaScript programming will enable you to fur-ther enhance and extend the Web applications you develop with ColdFusion.

    If you want to learn some JavaScript or review your knowledge, consider reading MasteringJavaScript and Jscript by James Jaworski or The ABCs of JavaScript by Leo Purcell and MaryJane Mara.

    If you plan to become a serious ColdFusion developer, you also need to understand rela-tional databases and how they work. Specifically, you will want to understand the basics ofdatabase design and table creation as well as the basic syntax and usage of the StructuredQuery Language (SQL), which is commonly used to query and manipulate data stored inrelational databases.

    You can gain a basic understanding of databases and how they work by reading a book onusing Microsoft Access such as Access 2000: No Experience Required by Celeste Robinson orMastering Access 2000 by Alan Simpson and Celeste Robinson. If you want to learn or reviewSQL, consider reading Mastering SQL by Martin Gruber. A SQL reference such as SQLInstant Reference, also by Martin Gruber, can prove useful when developing database-drivenapplications in ColdFusion.

    Finally, although learning ColdFusion doesnt require previous programming knowledgeor experience, having some will help you to more easily grasp ColdFusions structure and todesign and deploy large, complicated applications in ColdFusion.

    ColdFusion InstallationInstalling a complete ColdFusion system requires three steps:

    Installing a Web Server

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxx

  • xxxi

    Installing the ColdFusion Application Server

    Installing ColdFusion Studio

    These steps are covered in Appendix A, Installing ColdFusion.

    How This Book Is StructuredThis book is structured to take you from a quick introduction to the basics of ColdFusion (sothat you can quickly begin developing applications) and then right up to mastery of advancedtopics (so that you can become a ColdFusion expert).

    The book is divided into four parts:

    Part I teaches you how to create a basic ColdFusion file (or template) and then intro-duces the basics of retrieving information from a database and displaying to a Webbrowser using CFML. This will enable you to immediately begin developing dynamic,database-driven Web pages.

    Part II teaches you the core ColdFusion concepts and CFML syntax that are essentialto becoming a proficient ColdFusion developer. These include working with variables,functions, and expressions; creating interactive forms; working with databases; andusing the ColdFusion Web Application Framework.

    Part III concentrates on the way in which ColdFusion applications can interact withinformation services on the Web, including by uploading and downloading files fromFTP servers, by sending and retrieving e-mail messages, and by working with LDAPdirectory servers.

    Part IV addresses a range of advanced concepts, including ColdFusion scripting, eventscheduling, application security, and the ColdFusion Administrator. Weve also includedsix appendices that span installation, tag references, function references, and SQL func-tion references.

    If your goal is to learn ColdFusion without any prior knowledge of ColdFusion, then youshould read the chapters in order because the information presented in each chapter buildson knowledge gained in previous chapters. If you have prior ColdFusion experience, you willprobably find the first three chapters a good review. In this case, the book can be used as aneffective reference tool when you are developing applications in ColdFusion.

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxxi

  • xxxii

    Contents of the CDThis books CD includes several items that will be useful in learning ColdFusion, including:

    Selected source code listings from the book (those with headings, such as Listing 1.1)

    Complete evaluation versions of ColdFusion Application Server 5 and ColdFusionStudio 5 for Windows

    The Apache Web server

    Introduction

    2979fm.qxd 7/9/01 6:11 PM Page xxxii

  • The Basics Create your first ColdFusion template

    Pass data between ColdFusion templates

    Retrieve data from a database

    PART I

    2979c01.qxd 7/5/01 3:21 PM Page 1

  • 1CH A P T E R

    Creating Your FirstColdFusion Template

    Understanding CFML vs. HTML

    Using ColdFusion Studio

    Saving a file

    Using CFOUTPUT

    Using CFSET to create a variable

    Using ColdFusion functions

    Adding comments to your templates

    2979c01.qxd 7/5/01 3:21 PM Page 3

  • 4

    In this chapter, you will write your first ColdFusion template and learn the basic Cold-Fusion code that will prepare you for the rest of this book. Once you get started, coding yourfirst template should take you less than 15 minutes. Good luck and welcome to ColdFusion!

    NOTE A ColdFusion template is a text-based document that contains ColdFusion Markup Language(CFML), Hypertext Markup Language (HTML), and text. When the ColdFusion Server reads aColdFusion template it processes all of the CFML tags and replaces them with HTML outputthat is then sent to the browser. When a user requests a ColdFusion template in their browserURL field, they receive an HTML document stripped of ColdFusion tags.

    Get ReadyIn order to complete the exercises in this book, you need the following programs installed onyour computer:

    A Web server (for example, WebSite, Internet Information Server, Apache, PersonalWeb Server)

    ColdFusion Application Server 5

    ColdFusion Studio 4.5.2

    If you have been through the installation procedure described in the Introduction, con-tinue to the next section. Otherwise, please refer to Appendix A, Installing ColdFusion,and follow the directions for installation. If youre not sure whether you already have theseprograms installed, Appendix A can also help you verify the installation.

    Get SetNow that you have successfully installed a Web server, ColdFusion Application Server, andColdFusion Studio, you are ready to code your first ColdFusion template.

    Understanding CFML vs. HTMLCoding CFML is similar to coding HTML. CFML and HTML are both tag-based lan-guages that usually have beginning and ending tags. In fact, CFML has been designed towork seamlessly with HTML. However, they serve different purposes: CFML is used todetermine what content will appear on the page, whereas HTML is used to determine howthat content will be displayed.

    Chapter 1 Creating Your First ColdFusion Template

    2979c01.qxd 7/5/01 3:21 PM Page 4

  • 5

    TIP It is important to have a clear understanding of HTML and how it works before you continue.If you need to learn more about HTML, refer to the recommended books in the IntroductionsRequirements section.

    When coding a CFML template, you will use HTML and CFML together. So, a basicHTML page will become a ColdFusion template if CFML is added to the code. Here is abasic HTML tag:

    Now compare this to a basic CFML tag:

    As you can see, they have the same format. Of course, they perform different tasks, whichis exactly what this book will teach you.

    Using ColdFusion StudioColdFusion templates and HTML pages are both text-based documents that you can edit inany text editor. Throughout this book, you will edit all your templates using ColdFusion Stu-dio, Macromedias Web editor.

    NOTE ColdFusion Studio started out as an enhanced HTML editor called HomeSite, created by NickBradbury. In March 1997, Allaire acquired HomeSite, decided to expand on its features, andcreated a new product: ColdFusion Studio. Now, as part of the Macromedia line of products,ColdFusion Studio is a full-fledged Web-development editing application that integrates seam-lessly with ColdFusion Application Server. It enables you to track projects, add version control,preview Web pages, edit in WYSIWYG (What-You-See-Is-What-You-Get) mode, and muchmore. To learn more about Studio 4.5.2, refer to Chapter 22, Using ColdFusion Studio.

    To open ColdFusion Studio, click the Windows Start button and go to Programs Cold-Fusion Studio 4.5 (Program Group) ColdFusion Studio 4.5.

    NOTE The Programs menu lists ColdFusion Studio 4.5.2 as ColdFusion Studio 4.5.

    You can also click the Windows Start button and select Run. Then, in the Open field, typeC:\Program Files\Allaire\ColdFusion Studio 4.5\cfstudio45.exe or the path that cor-responds to the location where youve installed ColdFusion Studio.

    NOTE You can download the ColdFusion Studio 4.5.2 update from the Macromedia Web site andinstall it only over an existing installation of ColdFusion Studio 4.5 or 4.5.1. Version 4.5.2 pro-vides improved file-transferring capabilities, extended integration with third-party tools,enhanced resource management, and improved language capabilities. Youll find the updateat http://www.allaire.com/products/coldfusion/index.cfm after selecting the Cold-Fusion Studio 4.5.2 Available for Download link.

    Get Set

    2979c01.qxd 7/5/01 3:21 PM Page 5

  • 6

    When you open Studio, youll notice that an HTML page is already provided with all thenecessary head and body tags (see Figure 1.1). This is the page you will use to code your firstColdFusion template. You will also notice the Studio interface includes many toolbars andwindows. These will be explained as needed throughout the book, but if you would like moreinformation now, you can refer to Chapter 22.

    Saving a FileBefore you begin coding, follow these steps to save your file to a new directory:

    1. Go to File Save on the ColdFusion Studio menu bar.

    2. Make sure the Look In pull-down menu displays the Web server root directory.

    NOTE The Web server root directory should be the default directory. This directory may vary accord-ing to the Web server installed on your system. If your Web server root directory does notappear, or if you are not sure what it is, then use the following information to help you find itin the directory structure. The following are likely to be the default Web server root directoriesfor the most popular Web servers:

    WebSite C:\website\htdocsIIS C:\inetpub\wwwrootPWS C:\webshare\wwwrootApache C:\program files\apache group\apache\htdocs

    F I G U R E 1 . 1 :Interface for ColdFusionStudio 4.5.2

    Chapter 1 Creating Your First ColdFusion Template

    2979c01.qxd 7/5/01 3:21 PM Page 6

  • 7

    3. Now select the New Folder button to create a new folder in the Web server root direc-tory (see Figure 1.2).

    4. Rename this folder sybex and then open it by double-clicking the folder name.

    5. In the File Name text field, type home.cfm.

    6. Select the Save button.

    You have given this file a CFM extension so that the ColdFusion Application Server willrecognize it and process all the ColdFusion tags that you will eventually add to the file. For amore detailed description of how ColdFusion templates are processed, please refer to HowDoes ColdFusion Work? in the Introduction.

    Go!You are now going to add some text and ColdFusion code to your new home.cfm file. At thispoint, just add the code in Listing 1.1 to your new home.cfm file and follow the instructionsfor viewing the file. The code will be explained in the next section.

    NOTE You can find all of this books code listings in electronic format on the enclosed CD in theirrespective chapter folders. In some cases, you may need to rename the electronic version toreflect the examples in the book. For example, the file home1a.cfm is on the CD but should berenamed to home.cfm.

    F I G U R E 1 . 2 :Creating a new folder

    Go!

    2979c01.qxd 7/5/01 3:21 PM Page 7

  • 8

    Listing 1.1: home1a.cfm

    My Home Page

    Welcome to My Home Page!

    Todays date is:

    #today#

    You can view this file in your browser using the following URL: http://127.0.0.1/sybex/home.cfm. You should see a page similar to that shown in Figure 1.3.

    NOTE http://127.0.0.1/ is the URL that points to your local Web server root directory. You canuse this URL to browse any Web pages or Web sites stored on your local machine.

    F I G U R E 1 . 3 :Your first ColdFusiontemplate

    Chapter 1 Creating Your First ColdFusion Template

    2979c01.qxd 7/5/01 3:21 PM Page 8

  • 9

    You have just created your first ColdFusion template! Wasnt that easy? Lets now take acloser look at what you did.

    Using CFOUTPUTIn the preceding example, ColdFusion Studio provided you with the standard HTML tags tocreate a basic HTML page. You then added text and included todays date. Because HTMLdoes not provide a way to display dynamic (or changing) information such as the current date,you added ColdFusion code to display the date.

    ColdFusion tags and HTML tags are used similarly. Both languages usually have a begin-ning and an ending tag that encloses some information. Each set of beginning and endingtags always has the same name, except the ending tag name is preceded by a slash (/). In thiscase, you used one of the most basic of all ColdFusion tags, CFOUTPUT. This is one of the tagsyou can use when you want to display ColdFusion data. The CFOUTPUT tag tells the Cold-Fusion Application Server that it needs to evaluate all the ColdFusion variables between thebeginning and ending CFOUTPUT tags and then display it. The format for using a CFOUTPUT tagis written like this:

    In this space you can enter HTML, text, and/or ColdFusion code.

    For more information on the CFOUTPUT tag, please refer to the CFOUTPUT section in Appen-dix B, ColdFusion Tag Reference.

    Using CFSET to Create a VariableBetween your CFOUTPUT tags, you created a ColdFusion variable, called today, using theCFSET tag (refer to Listing 1.1). CFSET is used to create and modify variables, and its syntax iswritten as the following:

    For more information on CFSET, please refer to the CFSET section in Appendix B. You canalso refer to Chapter 4, Creating and Manipulating Variables.

    To understand variables, think of the stock market. Every stock has a unique name. Forexample, Macromedias stock has the name MACR. Now, almost every time you look at thevalue of the MACR stock on the NASDAQ Web site, it will have changed. So, the name ofthe stock is the same, but its value changes. In the same way, variables are given names, buttheir values can change. For example, you could create a variable named MACR with an initialvalue of 120. Over time, the value of the variable can change to 140, for example, withoutthe name changing. At any given time, the current value can be accessed through the variablename MACR.

    Go!

    2979c01.qxd 7/5/01 3:21 PM Page 9

  • 10

    In the previous example, you created the variable today and assigned it the value of Now().The value Now() is a ColdFusion function that returns the current timestamp (or the dateand time) that is recorded on the server (functions are discussed in more detail in the nextsection). If you were to reload your Web page, you would see a new timestamp because thevalue of the variable today has changed since you last loaded the home.cfm page.

    Several rules about variables are useful to know when coding your templates:

    ColdFusion variables that will be displayed in the browser usually need to be enclosedwithin pound (#) signsbut not always. For example, you did not have to enclose yourtoday variable within pound signs to set it, but you did have to enclose it within poundsigns to display it. Chapter 4, Creating and Manipulating Variables, provides moreinformation about when you should use pound signs with your variables. For now,when in doubt, use them.

    When you want to display a ColdFusion variable, it needs to be inside a CFOUTPUT tagor other similar tag (which you will learn about later in this book).

    ColdFusion variables cannot contain reserved words, spaces, or special characters andcannot begin with a number.

    For more information on ColdFusion variables, please refer to Chapter 4, Creating andManipulating Variables.

    Using ColdFusion FunctionsNow that youve taken a closer look at your first template, lets make some minor modifica-tions to it. Because the output of the today variable isnt in an easy-to-understand format,lets change it so that the date displayed looks something like Monday, March 12, 2001. Ofcourse, the date displayed will reflect the current date (based on your computers clock).Modify your CFSET tag to look like the following:

    Save your file and then reload the page in your browser.

    Now your date is in a more useful and readable format (see Figure 1.4), but how did youdo that? As explained before, the Now() function returns the current timestamp of the serverbut is difficult to decipher. To change the format so that it is easier to read, you have to mod-ify the date returned by the Now() function. So, you used another function, called the Date-Format function. The DateFormat function will modify any date passed to it to almost anyformat you want. Its syntax looks like this:

    DateFormat(date, format_of_date)

    Table 1.1 describes the two values that the DateFormat function takes.

    Chapter 1 Creating Your First ColdFusion Template

    2979c01.qxd 7/5/01 3:21 PM Page 10

  • 11

    TABLE 1.1: DateFormat Values

    Value Description

    date A valid date that you would like to be formatted. In the preceding example, you usedthe function Now(), which returns the current date.

    format_of_date This is where you specify the mask you want applied to the date (how you want thedate to be formatted). In the preceding example, you used the following masks:

    dddd Specifies the full name of the day of the week (Monday, Tuesday)

    mmmm Specifies the full name of the month (May, June)

    d Specifies the day of the month in a numeric value (1, 2, 3)

    yyyy Specifies the year in four digits (1998, 1999)

    You can mix and match these to create different formats. For a full description of themasks used for DateFormat, refer to the DateFormat section in Appendix C,ColdFusion Function Reference.

    So, in the following example:

    the variable today returns the following:Monday, March 12, 2001

    F I G U R E 1 . 4 :Your modified template

    Go!

    2979c01.qxd 7/5/01 3:21 PM Page 11

  • 12

    As you can see, ColdFusion functions perform an action. In this case, the Now() functionreturned the current timestamp. Other functions may, for example, format a string for you orfind a character within a string. (A string is an alphanumeric value. It can contain characters, spe-cial characters, and numbers.) The important concept to understand is that functions perform anaction and return a result. If youve used any other programming language, this may be familiarterritory. For more information on ColdFusion functions, please refer to Chapter 5, Functions.

    Adding Comments to Your TemplatesComments may already be familiar to you because of your background in HTML. They canhave many purposes, including the following:

    Allowing developers to explain their code

    Tracking changes within a document

    Tracking who has worked on a document

    Placing reminders to make changes or additions to the code

    Allowing a developer to debug code by isolating problem areas

    ColdFusion comment tags are akin to HTML comment tags. The only differencesbetween HTML and CFML comments are the following:

    ColdFusion code within an HTML comment is processed, whereas ColdFusion codewithin a CFML comment is treated as plain text.

    CFML comments are not displayed in the source code of the Web page document;they are stripped out before the final HTML file is rendered.

    CFML and HTML comments look similar. Here is an HTML comment:

    and here is a CFML comment:

    As you can tell, except for the extra dash (-), the format is the same. Also, CFML com-ments can span many lines, just like HTML comments can. It is only necessary that a CFMLcomment begin with .

    You are now going to add a CFML comment to your home.cfm file for the purpose ofexplaining your code. Modify the text between the CFOUTPUT tags in your home.cfm file toreflect the changes indicated in Listing 1.2.

    Two comment tags have been added to the template. You will notice that both commentsprovided quite a bit of information and spanned many lines. Comments are used extensivelyin ColdFusion to make the code easier to understand. Because every developer has a differentstyle of coding, comments are helpful in deciphering what others were trying to do with theircode. Good ColdFusion programmers always add comments to their code.

    Chapter 1 Creating Your First ColdFusion Template

    2979c01.qxd 7/5/01 3:21 PM Page 12

  • 13

    NOTE In Listing 1.2, all bold lines indicate where modifications have been made in the code. Thisconvention applies throughout the book.

    Listing 1.2: home1b.cfm

    My Home Page

    Welcome to My Home Page!

    Todays date is:

    #today#

    The first comment tag is a variation of a standard header tag used by many developers toprovide basic information about a template. Although not required, this represents good pro-gramming practices. The comment tag includes some basic information about the file thatmakes it easier and faster for any programmer to use. If the template produces an error, the

    Go!

    2979c01.qxd 7/5/01 3:21 PM Page 13

  • 14

    comment block makes it easy for anyone to tell who last modified it and when. A commentheader might include the following data:

    The application name as specified in the CFAPPLICATION tag (see Chapter 18 for moreinformation on the application framework).

    The person who owns or created the template.

    The type of filewhether it is a standard template, included template, custom tag, andso on.

    A brief description of what the template does, how a user might get there, and wherethey can go.

    Modifications that have been made to the template, including the date, time, andauthor. You can flush modification list entries if the list becomes too lengthy.

    The second comment tag described how the Now() function was used to display the current date.

    Now, if you save and reload your page in the browser, you wont see any changes. And ifyou look at the source code, you still wont see any changes. This is because CFML com-ments do not appear to the end user, even in the source. If you were to change the CFMLcomment to an HTML comment, it would, of course, appear in the browsers source code.CFML comments appear only to the developers who have access to the original code.

    You added the comment tag so that when you refer to this file later, you will understandthe purpose of this template and how you coded the today variable. ColdFusion commentscan be extremely useful in documenting your code while also keeping your coding secretsprivate from end users.

    Where Do We Go from Here?In this chapter, you created your first ColdFusion template. Although it wasnt very elabo-rate, it showed you these basic concepts for coding ColdFusion templates:

    Understanding variables

    Creating variables

    Displaying variables

    Understanding functions

    Using functions

    Commenting your code

    In the next chapter, you will learn how to pass data from one template to another usingHTML forms and hyperlinks.

    Chapter 1 Creating Your First ColdFusion Template

    2979c01.qxd 7/5/01 3:21 PM Page 14

  • 2CH A P T E R

    Passing Data betweenColdFusion Templates

    Passing ColdFusion parameters: an overview

    Passing parameters through a URL

    Evaluating variables

    Passing parameters through a form

    2979c02.qxd 7/5/01 3:22 PM Page 15

  • 16

    Now that you have created your first ColdFusion template, you are ready to learn how to pass parametersthe values of variables passed through a URL or a formbetweentwo ColdFusion templates. This chapter will provide an overview of how to pass parametersbetween ColdFusion templates using URLs and forms. You will also learn how to control theflow of your document using the CFIF tag. This chapter builds upon the HTML knowledgeyou already have and shows you how much more you can do using ColdFusion.

    Passing ColdFusion Parameters: An OverviewIf youre using HTML, you have no way to pass data between pages or store information invariables (values assigned either by you, the developer, or the ColdFusion environment in agiven template). This results in a static Web site without much interactivity. The most youcan do on an interactive basis is let the user navigate to other pages, submit forms (which canonly be sent unformatted to an e-mail address), and send e-mail (provided the users browseris configured appropriately).

    Once you are able to pass data between HTML pages and then store the data in variables,you can create much more interactivity on your Web site. For example, some of the things youcould do include the following:

    Create a form that requests information from users, then display that information onthe following page while additionally storing the information in variables or a databasefor later use

    Program a quiz, evaluate user answers, and keep track of scores

    Track which pages a user has visited on your site

    Redirect users to different locations based on variable contents

    You may already have worked with other technologies that let you create this type of inter-activity. For example, JavaScript can pass data between HTML pages. You can also use Com-mon Gateway Interface (CGI) programming, Active Server Pages (ASP), and a whole host ofother technologies. ColdFusion, though, is generally much easier to use and learn, especiallyfor someone who has never programmed before. Also, ColdFusion offers advantages over allthese technologies because it allows for database interaction (which is covered in Chapter 3,Retrieving Data from a Database).

    In this chapter, you will create a short quiz using variables, URL parameters, and formparameters.

    TIP Remember, you should have a thorough understanding of HTML, URLs, and forms before con-tinuing. If you need to learn more about HTML, URLs, or forms, refer to the book recommen-dations in the Introductions Requirements section.

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:22 PM Page 16

  • 17

    Passing Parameters through a URLYou are already familiar with how to create a basic hypertext link that lets a user navigate tovarious pages on the Web. In the next example, you will be using hypertext links to allow foruser navigation while also passing parameters to the next ColdFusion template. This can bedone through a URL or a form.

    Creating a Basic ColdFusion URLTo pass a parameter to another template, you must separate the standard URL from theparameters you are passing with a question mark (?). The question mark is then followed bythe name of the parameter equal to the value of the parameterin this case, answer=1985. Thesyntax for passing a parameter to the next template is as follows:

    If you want to pass more than one parameter, you must separate each with an ampersand(&), as in the following example:

    In the home.cfm file that you created in Chapter 1, Creating Your First ColdFusion Tem-plate, you can now add the code in Listing 2.1.

    NOTE In Listing 2.1, all bold lines indicate where modifications have been made in the code. Youneed to make changes only to these lines in your template. This convention applies through-out the book.

    Listing 2.1: home2a.cfm

    My Home Page

    Welcome to My Home Page!

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:22 PM Page 17

  • 18

    Todays date is:

    #today#

    Todays question is:In what year was ColdFusion introduced?

    1985199019951998

    When viewed in your browser, the file should look like Figure 2.1.

    If you take a closer look at home.cfm, you will notice that the four possible answers to thequiz question all link to the same page, quiz_results.cfm. You will also notice that addi-tional data has been appended to the standard URL, making each link slightly different. Thisdata is the user_answer parameter that you are passing to the next template.

    F I G U R E 2 . 1 :Multiple-choice quiz

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:22 PM Page 18

  • 19

    Now, to test the home.cfm page, you need to first create quiz_results.cfm. Inquiz_results.cfm you will display the users selected answer and the correct answer. Createthe template shown in Listing 2.2 in ColdFusion Studio by selecting File New DefaultTemplate. Then save the file to the sybex directory as quiz_results.cfm.

    When naming your own ColdFusion templates remember the following:

    Filenames should not contain spaces or special characters.

    Filenames should begin with a letter.

    Filenames should only contain letters, numbers, and underscores.

    In a Unix environment, filenames are case-sensitive. So home.cfm is a different file thanHome.cfm. Remember this when naming and referencing your files.

    Try and give your templates meaningful names. This will make it easier for you toremember the template contents.

    Give your filename a CFM extension indicating it is a ColdFusion template.

    TIP Remember that ColdFusion variables must be enclosed in pound (#) signs and surrounded by aCFOUTPUT tag set.

    Listing 2.2: quiz_results2a.cfm

    Quiz Results

    Quiz Results!Thank you for taking my short quiz!

    The question was:In what year was ColdFusion introduced?

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:22 PM Page 19

  • 20

    Your answer was: #URL.user_answer#The correct answer is: 1995

    Take the quiz again?

    Now reload the home.cfm file in your browser and select the first answer, 1985. You will bedirected to the file quiz_results.cfm, which should look like Figure 2.2.

    You have just passed your first parameter from one template to another through a URL. Ifyou look at the URL in the browsers location, you will notice it also contains the passedparameter. ColdFusion reads this URL when the template is being processed and assigns allthe URL parameters to variable names in the following format: URL.parameter_name. Youcan then access the generated variable later in the template, which is exactly what you did.When you coded which year the user chose as #URL.user_answer#, you accessed the variableURL.user_answer. ColdFusion generated this variable when it parsed the parameter in the URL.

    This variable is part of the URL scope. Variable scope defines where and for how long avariable exists. A variable with the URL scope exists only for the page to which it was sent.Table 2.1 lists some other examples of variable scopes. You will be learning about URL andform variables later in this chapter. You can learn more about the types of variables you canset and their scopes in Chapter 4, Creating and Manipulating Variables.

    F I G U R E 2 . 2 :Your quiz results

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:22 PM Page 20

  • 21

    TABLE 2.1: Variable Scopes

    Scope Format Description

    Local VARIABLES.variable_name Variables created in a template and accessible only within thetemplate

    Query query_name.variable_name Variables created as a result of a query to a data source, suchas a database or mail server

    CGI CGI.variable_name Variables supplied by the server (contains variables such asusers IP address and users browser version)

    File FILE.variable_name Variables associated with an uploaded file

    URL URL.variable_name Variables passed through a URL

    Form FORM.variable_name Variables passed through a form submission

    Cookie COOKIE.variable_name Variables created from a browser cookie

    Client CLIENT.variable_name Persistent variables stored until deleted

    Request REQUEST.variable_name Variables created in a template and accessible by all templateassociated with that page request (includes custom tags,included files, etc.)

    Session SESSION.variable_name Variables stored during the current browser session

    Application APPLICATION.variable_name Variables applied to all templates in an application

    Server SERVER.variable_name Variables associated with the ColdFusion server and availablein all applications running on the server

    This was, of course, a simple example. You passed a parameter from one template toanother and then displayed the generated variable to the user. It would be much more usefulif you could evaluate the value of that parameter and then display different messages basedon the data passed. You will learn how to do exactly this later in this chapter.

    Working with Multiple ParametersIn this section, you will expand on the previous example by passing four parameters with dif-ferent characteristics through a URL. Before modifying your code, it is important to look ateach of the parameters you will pass in this example.

    In the previous example, you passed only the user_answer parameter. The only benefitgained was to display the answer to the user on the next page. Everything else on the quiz_results.cfm file was hard-coded. But what if your ultimate goal is to create a quiz with ran-domly generated questions or multiple questions on the first template? If that is your goal,then you cannot hard-code the question and the correct answer on your second template (as was done in the previous example) because the question and answer could be differenteach time.

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:22 PM Page 21

  • 22

    You will be adding an additional quiz question to your home.cfm file to illustrate this point.This will enable you to pass different quiz question variables through a URL. You will bemodifying your code so that the following variables will be passed through each of the URLs:

    question The full text of the question the user has chosen

    user_answer The answer chosen by the user

    correct_answer The correct answer

    today The variable today that you created in Chapter 1

    First, you need to create your variables in your home.cfm file. You already created the todayvariable in Chapter 1. The user_answer variable will be selected by the end user as part of theURL, as demonstrated in the preceding section. To create the question and correct_answervariables and to add an additional question, modify the code in your home.cfm file as shown inListing 2.3.

    Listing 2.3: home2b.cfm

    My Home Page

    Welcome to My Home Page!

    Todays date is:

    #today#

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:22 PM Page 22

  • 23

    Todays 1st question is:#question1#

    1985199019951998

    Todays 2nd question is:#question2#

    Kristin

    Aileen MotlaghJ.J.

    AllaireArman

    DaneshRaymond

    Camden

    TIP If you are assigning a text string to a variable, you should surround the text string in quotemarks (). You do not need to do this with numbers. For more information on variables,please refer to Chapter 4, Creating and Manipulating Variables.

    Here is what you just did to your template:

    1. Added a comment line explaining where the code for each quiz question started

    2. Set the question1 and correct_answer1 variables for question 1

    3. Changed from displaying a hard-coded question to displaying the question1 variable

    4. Added code for the second question and repeated steps 13 for the second question

    TIP If you need to set three or more variables at one time, it is more efficient to create them in aCFSCRIPT block. For more information on CFSCRIPT, please refer to Chapter 29, EvaluatingDynamic Expressions.

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:22 PM Page 23

  • 24

    Now that you have all your variables set, you are ready to add them as parameters to theURLs in your home.cfm file. Lets add each parameter one at a time to the first URL in yourfirst question. Your current URL format looks like this:

    1985

    You are already passing the user_answer parameter. This parameter is hard-coded into theURL. Now you can add the correct_answer parameter. But, because the correct_answerparameter is not hard-coded and its value is equal to the ColdFusion variablecorrect_answer1 that you set earlier in the template, you will need to output it in the URLusing CFOUTPUT tags. Here is the resulting code:

    1985

    The question parameter is like the correct_answer parameter in that it is not hard-coded.Now, add the question parameter in the same manner:

    1985

    Finally, you can add the today parameter:1985

    Youre not quite finished yet. You now need to complete the same set of steps for the otherthree URLs in the first question and the rest of the URLs in the second question. Rememberthat you need only one CFOUTPUT tag set to surround all of your ColdFusion variables. You donot need a separate CFOUTPUT tag set for each variable. In fact, using multiple CFOUTPUT tagscan slow the performance of the ColdFusion server.

    Your final file should look like Listing 2.4.

    Listing 2.4: home2c.cfm

  • 25

    - 03/21/2001 23:51 - KM - Added quiz question- 03/22/2001 00:16 - KM - Added new quiz question. Modified URLs- 03/22/2001 00:26 - KM - Fixed URLs--->

    My Home Page

    Welcome to My Home Page!

    Todays date is:

    #today#

    Todays 1st question is:

    #question1#

    1985199019951998

    Todays 2nd question is:

    #question2#

    KristinAileen Motlagh

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:22 PM Page 25

  • 26

    J.J. Allaire

    Arman Danesh

    Raymond Camden

    To test your changes, you also need to make some changes to your second template,quiz_results.cfm. Because you are no longer hard-coding any of the quiz data on the sec-ond template, you need to remove the quiz question and answer from the second templateand replace them with the variables generated from the parameters passed through a URL.The variables generated are as follows:

    URL.user_answer

    URL.correct_answer

    URL.question

    URL.today

    NOTE You do not need to specify the URL scope prefix if there are no conflicting variable names;however, it is good coding practice to do so. By specifying the variable scope, it is easy to seewhere a variable comes from as well as how and when it can be used. Refer to Chapter 4,Creating and Manipulating Variables, for additional information on variable scope.

    Modify your quiz_results.cfm as shown in Listing 2.5.

    Listing 2.5: quiz_results2b.cfm

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:22 PM Page 26

  • 27

    Quiz Results

    Quiz Results!Thank you for taking my short quiz!

    The question was: #question#Your answer was: #user_answer#The correct answer is: #correct_answer#You took the quiz on: #today#

    Take the quiz again?

    In this file, you added the date the quiz was taken, and you changed the question and correctanswer from hard-coded values to the output of variables generated from the URL parame-ters. Now, reload the home.cfm file in your browser. You will notice that the value displayed inthe status window when you put your mouse over the URL has changed (see Figure 2.3).

    F I G U R E 2 . 3 :Your new quiz

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:23 PM Page 27

  • 28

    Now, select the first answer to the first question. What do you see? If youre using InternetExplorer or above, your page should look like Figure 2.4.

    If you are using a browser other than Internet Explorer 4 or above, you may have receivedyour first ColdFusion error. In some browsers, spaces within URL parameters are not auto-matically resolved like they are in Internet Explorer 4 and above. If you received an error, itprobably looks something like this:

    Error Diagnostic Information

    Error resolving parameter TODAY

    ColdFusion was unable to determine the value of the parameter.This problem is verylikely due to the fact that either:

    1.You have misspelled the parameter name, or2.You have not specified a QUERY attribute for a CFOUTPUT, CFMAIL, or

    CFTABLE tag.

    The error occurred while evaluating the expression:

    #today#

    The error occurred while processing an element with a general identifier of(#today#),occupying document position (29:33) to (29:40) in the template filec:\inetpub\wwwroot\sybex\quiz_results.cfm.

    F I G U R E 2 . 4 :Your dynamic quiz results

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 28

  • 29

    Date/Time: 03/22/01 01:44:19Browser: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)Remote Address: 127.0.0.1HTTP Referrer: http://127.0.0.1/sybex/home.cfmTemplate: c:\inetpub\wwwroot\sybex\quiz_results.cfmQuery String: user_answer=1985&correct_answer=1995&question=In

    Thats a pretty long error message with a lot of information that, at this point, may notmake a lot of sense. But it does provide all the information you need to figure out the prob-lem. Look at the entire text of the error for a minute or so and see if you can figure out theproblem for yourself.

    NOTE If you didnt receive the error because you are using a browser that resolves URL spaces, it isstill important to read this section. Users with a wide range of browsers can visit your Websites and may come across an error you are unable to see with your own browser. This is why itis important to test all of your code using a variety of popular Web browsers.

    You know from the error message that ColdFusion had a problem processing the todayparameter. When the ColdFusion processor came across the variable today, it searched forthe value (the one you passed through the URL) but could not find it. If you look at the lastline of the error message, you will see that the today parameter was never passed. In fact, thequestion parameter was not completely passed either. This is because you cannot pass certaincharacters, such as spaces, through a URL in some browsers. When you passed the questionparameter through the URL, its value contained spaces, and the browser did not understandhow to process it. As a result, the URL was truncated at the first space received in the URL.

    To preserve the value of parameters passed through a URL, you must convert the illegalcharacters to characters that all browsers can better interpret. ColdFusion enables you to dothis with the function URLEncodedFormat. (For more information on URLEncodedFormat, pleaserefer to the URLEncodedFormat section in Appendix C, ColdFusion Function Reference.)

    In Chapter 1 you learned a bit about ColdFusion functions. Here, the URLEncodedFormatfunction is used similarly to the way that the DateFormat function was used in Chapter 1.Remember that functions perform an action and return a result. You must apply the URLEn-codedFormat function to the parameter you are passing in the following manner:

    #URLEncodedFormat(parameter_name)#

    So, if you apply this concept to your home.cfm file, the first link in your file should look like this:

    1985

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:23 PM Page 29

  • 30

    Modify all the links in your home.cfm file as demonstrated in the preceding code. It isimportant that you always apply the URLEncodedFormat function to each of the parameters(even if they are hard-coded) because they could possibly be changed and contain illegalcharacters at some time in the future. You will also notice that the hard-coded answers forthe second question contain spaces and may therefore cause an error if you do not apply theURLEncodedFormat function to them.

    If you previously received an error, you can now reload the home.cfm file in your browserand test the links. When you link to the quiz_results.cfm file, it should now look similar toFigure 2.4.

    Your final template should look like Listing 2.6.

    Listing 2.6: home2d.cfm

    My Home Page

    Welcome to My Home Page!

    Todays date is:

    #today#

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 30

  • 31

    Todays 1st question is:

    #question1#

    1985

    1990

    1995

    1998

    Todays 2nd question is:

    #question2#

    Kristin Aileen Motlagh

    J.J. Allaire

    Arman Danesh

    Raymond Camden

    Passing Parameters through a URL

    2979c02.qxd 7/5/01 3:23 PM Page 31

  • 32

    In this section, you learned to pass multiple parameters through a URL. Some rules toremember when you pass parameters through a URL are:

    You must use a question mark (?) to separate your standard URL from the parametersyou are passing.

    You must separate each passed parameter with an ampersand (&).

    You must always use URLEncodedFormat when passing parameters through a URL toavoid problems with illegal characters.

    You must always use pound (#) signs to surround variables included in a link.

    If you include variables in your link, you must surround the link with CFOUTPUT tags.

    Evaluating VariablesAt this point, you have been able to do quite a bit more with ColdFusion than you could dowith basic HTML, but there is still much more you can do. Although you have been able toprovide minimal feedback to users in our quiz example, you havent really been able to tellthem how well they are doing. You havent been able to evaluate the content of any variables.Being able to evaluate variables enables you to:

    Compare the value of one variable against another

    Execute a set of code based on the value of a variable or comparison of variables

    Account for nonexistent variables

    Control the flow and display of your template

    Abort the processing of a template based on the value of a variable

    In this section, you will expand the quiz application to provide valuable feedback to theuser about their quiz results, control what is displayed in the template based on the usersquiz results, and prevent errors by accounting for nonexistent variables.

    Controlling the Display of Your Template Using CFIFYou will now use basic ColdFusion logic to evaluate the users answers. If the users answersare correct, then you will display a congratulatory statement. If they are incorrect, you willask the user to try again. To create this interaction, you need to evaluate whether theuser_answer variable is equal to the correct_answer variable. You can accomplish this byusing CFIF statements. (For more information on CFIF, please refer to the CFIF section inChapter 7, Controlling the Flow of Your Templates.)

    NOTE It is sometimes better to use CFSWITCH and CFCASE instead of CFIF and CFELSEIF tags. SeeChapter 7, Controlling the Flow of Your Templates, for additional information.

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 32

  • 33

    The CFIF statement has both a beginning and ending tag and may also include the CFELSEand CFELSEIF tags. The format for using CFIF is as follows:

    Do this

    Then do this

    Or do this

    So, in your quiz_results.cfm file, you can evaluate whether the users answer is the sameas the correct answer by modifying your code as shown in Listing 2.7.

    Listing 2.7: quiz_results2c.cfm

    Quiz Results

    Quiz Results!Thank you for taking my short quiz!

    Congratulations!!!You are correct!

    Im sorry, but that is the wrong answer.Please try again.

    The question was: #question#

    Your answer was: #user_answer#

    The correct answer is:

    Evaluating Variables

    2979c02.qxd 7/5/01 3:23 PM Page 33

  • 34

    #correct_answer#

    You took the quiz on: #today#

    Take the quiz again?

    Now reload your home.cfm file and take the quiz. When you select the correct answer, youshould be congratulated. When you select the wrong answer, you should be asked to tryagain and the correct answer should be hidden from you (see Figure 2.5).

    This is what you did to create this interaction:

    1. Using CFIF, you evaluated whether user_answer was equal to correct_answer. If itevaluated to be True, then the next set of HTML and ColdFusion code was processedup until the CFELSE tag. The code following the CFELSE tag up until the ending tag was ignored because it didnt evaluate to True. The opposite would be true if yourinitial CFIF statement evaluated to False.

    2. You added color to increase the dramatic effect of correct or incorrect answers.

    3. You displayed the user_answer variable only if the user had chosen the incorrect answer.

    4. You displayed the correct_answer variable only if the user had chosen the correctanswer. This way, a user who chooses the incorrect answer can still try again withoutseeing the correct answer first.

    F I G U R E 2 . 5 :Evaluating user input

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 34

  • 35

    Accounting for Nonexistent VariablesNow that you are able to evaluate variables, you are also able to determine whether theyexist. If a variable does not exist, but your template calls that variable, ColdFusion will pro-duce, or throw, an error. So far in the application, this has not been a problem. But thisbecomes a problem if someone decides to link to your quiz_results.cfm file directly withoutfirst going to the home.cfm file.

    Try opening the URL http://127.0.0.1/sybex/quiz_results.cfm and you will see anerror. The reason is that parameters have not been passed to the template through a URL.Even though it is unlikely that anyone will try to access this template directly, it is a possibil-ity, and therefore you must account for it.

    To account for nonexistent variables, you need to first evaluate whether the variables existin the template. You can do this using CFIF and the ColdFusion function IsDefined. (Formore information on IsDefined, please refer to the IsDefined section in Appendix C,ColdFusion Function Reference.)

    The format used to evaluate if a variable exists is as follows:

    The format used to evaluate if a variable does not exist is as follows:

    You can evaluate if multiple variables exist using the following syntax:

    In the quiz, four variables are referenced in the quiz_results.cfm file. To evaluate if allfour variables exist, add the code in Listing 2.8 to the quiz_results.cfm file immediatelyafter the BODY tag. Additional information about controlling the flow of your template can befound in Chapter 7, Controlling the Flow of Your Templates.

    Listing 2.8: quiz_results2d.cfm

    Welcome!Please take my quiz!

    Evaluating Variables

    2979c02.qxd 7/5/01 3:23 PM Page 35

  • 36

    NOTE You can find the full template for Listing 2.8 on this books CD under the namequiz_results2d.cfm.

    Now if you load http://127.0.0.1/sybex/quiz_results.cfm, you will see a link back tothe main quiz page instead of an error (see Figure 2.6). The code you just added to thequiz_results.cfm template checks whether any of the four variables are missing. If even oneis missing, the processing of the template is aborted. Whenever you want to abort the pro-cessing of a template, you can use the ColdFusion tag CFABORT. (For more information onCFABORT, please refer to CFABORT in Appendix B, ColdFusion Tag Reference.)

    Passing Parameters through a FormThe quiz you have created still has one major problem: A user can view the correct_answerparameter in the browsers status bar when they pass their mouse over a link in the home.cfmfile. They can also view all the parameters in the location bar of the browser when thequiz_result.cfm file is displayed. Obviously, giving the answers away defeats the purpose oftaking a quiz. To solve this problem, you can convert your quiz to a form-based application.In a form, parameters are passed through a form submission, which does not appear in theURL location bar. Unfortunately, users can still view the correct answer by looking at thepages source code. In the next chapter you will learn how to prevent this.

    So, for this example, you will use radio buttons and a submit button for each question toenable the user to take the quiz. This is a fairly simple example using your backgroundHTML knowledge on forms. You can now modify your home.cfm file to convert each ques-tion to a separate form, as shown in Listing 2.9.

    NOTE You should always use the post method for submitting a form that passes parameters to aColdFusion template.

    F I G U R E 2 . 6 :Accounting for nonexistentvariables

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 36

  • 37

    Listing 2.9: home2e.cfm

    My Home Page

    Welcome to My Home Page!

    Todays date is:

    #today#

    Todays 1st question is:

    #question1#

    1985 1990

    Passing Parameters through a Form

    2979c02.qxd 7/5/01 3:23 PM Page 37

  • 38

    1995 1998

    Todays 2nd question is:

    #question2#

    Kristin Aileen Motlagh

    J.J. Allaire Arman Danesh Raymond

    Camden

    You just drastically changed your home.cfm file. In this new version, you are now passing allyour parameters through form fields instead of through a URL. This also means you nolonger need to use the URLEncodedFormat function. The user_answer variable is now passedusing radio buttons. The correct_answer, question, and today variables are each passed usinghidden form fields. In this example, you made each question its own form with its own sub-mit button because you have not provided for the handling of multiple questions in thequiz_results.cfm file. Also, in the next chapter, you will be displaying only one randomlygenerated question pulled from a database, so there is no need to accommodate multiplequestions now.

    Now, test your quiz. Your home.cfm file should look like Figure 2.7, but your quiz_results.cfm file should look the same as it did before. If you had hard-coded the URL prefix

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 38

  • 39

    to the variables in the quiz_results.cfm file, it would have produced an error now that youare using forms. When form parameters are processed by the ColdFusion server, they areassigned to variable names in the following format: form.variable_name. But, as with URLvariables, you do not need to specify the prefix unless there is a conflicting variable name inthe template. Therefore, ColdFusion is able to evaluate either form or URL variables in thesame way if the prefixes have not been specified. You should remove the URL prefixes fromyour variables or change them to form prefixes if needed.

    In the quiz, you have not accounted for the possibility that a user could choose to submit aform without selecting a radio button. Normally, this would result in an error because allparameters required by the following template would not be passed through a URL. But,because you added code to evaluate the existence of all required variables in the quiz_results.cfm file, the user will not receive an error, just a pointer back to the quiz. This is atype of validation. If you would like to learn more about form validation using ColdFusion,you can refer to Chapter 17, Validating Form Data.

    F I G U R E 2 . 7 :Your new form-based quiz

    Passing Parameters through a Form

    2979c02.qxd 7/5/01 3:23 PM Page 39

  • 40

    Where Do We Go from Here?In this chapter, you created your first ColdFusion application. In creating this application,you learned the following techniques and concepts:

    Understanding the difference between parameters and variables

    Passing parameters through a URL

    Displaying parameters passed through a URL

    Using the URLEncodedFormat function to preserve URL integrity

    Evaluating variables with the CFIF tag construct

    Using the IsDefined function to evaluate the existence of a variable

    Aborting the processing of a template using CFABORT

    Passing parameters using regular HTML forms

    In the next chapter, you will convert your quiz into a database-driven application that pullsall its data from a database.

    Chapter 2 Passing Data between ColdFusion Templates

    2979c02.qxd 7/5/01 3:23 PM Page 40

  • 3CH A P T E R

    Retrieving Data froma Database

    Setting up a database

    Querying a database

    Validating form input

    2979c03.qxd 7/5/01 3:24 PM Page 41

  • 42

    The true power behind ColdFusion is its capability to access and manipulate databaserecords. In this chapter, you will learn how to access a database using ColdFusion and how touse basic Structured Query Language (SQL) to retrieve information from a database. Youwill be working with a Microsoft Access 2000 database provided on this books CD. It is notessential that you have Access 2000 in order to continue, but it would be useful.

    WARNING Macromedia and Microsoft give strong recommendations against using Microsoft Access in aproduction environment. Microsoft Access is best used for small, low-traffic Web sites. Pleaserefer to this Macromedia Knowledge Base article for more information: http://www.allaire.com/Handlers/index.cfm?ID=1540&Method=Full.

    Setting Up a DatabaseBefore ColdFusion can interact with a database, you must set up a ColdFusion data source inthe ColdFusion Administrator. A data source is essentially a pointer to the physical database.In a sense, it is the source path for the data you want to access. You have to set up a Cold-Fusion data source only once for each database with which you need to work. You will beworking with the ColdFusion Administrator to set up the data source.

    NOTE ColdFusion 5 now provides the ability to dynamically connect to an ODBC-compliant databasewithout having a predefined data source. (ODBC stands for Open Database Connectivity,which is a standard protocol used with most databases to allow for outside access.) You canlearn more about this new feature in Chapter 11, Using Advanced Query Techniques.

    A Basic Access DatabaseYou will use the sybex.mdb database for all of the exercises in this book. This database con-tains a variety of tables used in various chapters. In this chapter, you will be using only thequestions table. It is a simple table containing seven columns. If you have Access 2000, youcan open the database to view it (see Figure 3.1).

    NOTE You can find the sybex.mdb database on this books CD. Please save the database to thesybex folder in your Web server root directory.

    The questions table is where you will store and retrieve all the data needed for the exer-cises during this chapter. If you are viewing the database in Access, double-click the table toopen it; otherwise, refer to Figure 3.2.

    Chapter 3 Retrieving Data from a Database

    2979c03.qxd 7/5/01 3:24 PM Page 42

  • 43

    The questions table contains seven columns and 10 rows. If you have never worked withdatabases, you will need a basic understanding of them before you continue. If you haveworked with databases, please proceed to the section titled Using the Administrator to Adda Data Source.

    What Is a Database?A database provides a way to store categories of information in an organized, easily accessibleformat. In Chapter 2, Passing Data between ColdFusion


Recommended