ColdFusion MX is the newest version of an already fantastic product developed by Macromedia, arguably the biggest and best producer of Web software out there. CFMX, as it’s commonly referred to, is built on top of J2EE (Java 2 Enterprise Edition), and as a result, is much more robust that previous versions of ColdFusion. If you are wondering whether or not you should upgrade that old copy of 3.1 you still have lying around, the answer is a resounding “yes!”
If you’re just starting out, you probably have a bunch of questions. “Just what is ColdFusion? Do I need to know Java since it is built on J2EE? Why should I use CFMX instead of ASP or other free scripting language?” Let me answer these questions one at a time:
- First of all, ColdFusion MX is a fully functional application server. CFMX will work in conjunction with most popular Web server software available, including Apache, IIS and Deerfield Website. Think of it like this: let’s say you use IIS. In this scenario IIS will act as the batter in a baseball game. The pitcher is a Web user and ColdFusion is the catcher.
In a typical “game”, the user “pitches” an http request for an html page and the batter (that’s the Web server software) hits the request back to the user. With CFMX, a user “pitches” a request for a ColdFusion file. The Web server steps back and let’s the catcher (ColdFusion) take the CFML request and pass it back to the user. I know this analogy is a bit odd but it usually helps illustrate where CFMX fits into the picture.
Secondly, ColdFusion is a powerful server-side scripting language. And believe me, it’s as robust as any language out there. This language consists of tags similar to HTML tags, and FUNCTIONS similar to those found in Visual Basic.
- Third in this line of questions is “Why should I use CFMX instead of another free scripting language?”. I believe that Ben Forta answered that question with a bang in a recent issue of ColdFusion Developer’s Journal. The short version is “you get what you pay for” and CFMX, while it’s not cheap, does deliver a boat-load of features that would cost you many times the price of CFMX in another “free” language.
- Do you need to know Java to use CFMX? No. CFML puts a simple and easy to use language between you and cumbersome Java.
Ok, enough already! Let’s get coding!
I’ve already said that CFML is similar to HTML, but what’s the difference between HTML and CFML? Simple. All ColdFusion tags start with the letters “CF”, allowing you to tell what’s static HTML and what’s ColdFusion code. When ColdFusion reads a CFML page and comes across a ColdFusion tag, it performs the specified task, and returns HTML to the end user. One of the reasons that CFML is so powerful is that it works perfectly with existing HTML. You may embed CF tags into your static HTML and even use ColdFusion to write HTML code for you in many cases. Let’s give it a try.
Lesson 1: The Simple Art of CFML
Let’s start this off with perhaps the most basic and heavily used ColdFusion tag:
The “cfoutput” tag allows tells ColdFusion Server to “output” or display data between these tags. By itself,
<CFOUTPUT> is useless, but if you combine it with double pound-signs (##), it becomes the basis for the CFML language structure. A completed output tag would appear something like this:
Note: You cannot place cfoutput tags inside other cfoutput tags as a rule. If you do, you will receive an error to tell you that you have invalidly nested cfoutput tags. There is a way and reason to do this, but it goes beyond the scope of this simple tutorial.
Now, let’s produce a simple output. With most programming languages. you always seem to learn a “Hello World” script first, so let’s start with this:
- Make sure that you have installed CFMX.
- Be sure that ColdFusion MX Service is running.
- Create a new folder named Lesson1 under the Webroot of the CFMX Server. C:CFUSIONMXWWWROOTLESSON1
- Open Cold Fusion Studio or another of your favorite text editors. I recommend ColdFusion Studio or Homesite for this function. You can also use Dreamweaver MX in code-view. This lesson will not refer to any of the visual CFML in that application.
- Create a new blank CFML page. It will look the same as a blank HTML document.
- Save this file into your new folder as INDEX.CFM
- In between the
<BODY></BODY>tags, just as you would in HTML, enter the following code:
<CFSET MyWorld = 'Hello World'> <CFOUTPUT>#MyWorld#</CFOUTPUT>
- View the page by opening your browser and entering your IP address (127.0.0.1 in most cases), followed by port 8500 and the folder Lesson1. It should appear like this:
Great! Now, let’s break this code sample down:
Breaking Down the Code Sample
<CFSET MyWorld = 'Hello World'>creates a variable and value on the page you are viewing. In this specific case we've created a variable named "MyWorld" and assigned it the value "Hello World". In ColdFusion, as in all programming languages, the variable is equal to its value. So MyWorld will process as "Hello World". Whenever you need to use this variable on this template and this template only, you may "call" the variable into action with the above
CFOUTPUTblock. Once you leave this page, the variable dies and must either be reset with
CFSET, or passed via the query string.
The name I chose, "MyWorld", is no magic name... it doesn't have any mystical programming properties at all. You could name your variable "clownshoes" if you felt the desire to do so. Using the
<CFSET>tag as I have above, there are a few basic guidelines that you may wish to follow.
- ColdFusion variable names are NOT case sensitive.
- ColdFusion variables are typeless. You do not need to declare whether a variable is a string, number, etc.
- Consider typing your variable names in "title case" where every word starts with a capital letter, similar to JackPoe or ColdFusion. This just makes it easier to read them. Feel free to adopt any coding practice you see fit, however, you should pick one naming practice and stick to it from here on out.
- Never ever use spaces or punctuation in your variable names... ever.
- Your variable name should not start with a number.
- Make your variable names easy to remember and short (when possible). This makes them easier to remember and quicker to type. Avoid creating variable names like "MyThirdVariableHere". If you have to type that a few dozen times it will get tiring quite fast.
So, to quickly recap and diagram a typical
<CFSET MyScript = 'Hello Papa Smurf'> The tag being used The variable name The value you are assigning to the variable
Now let's look at the
You will notice that the variable name is encased in double pound signs or hash marks: ##. If you'll play along with the analogy, these are like ColdFusion's "fingerprints". The ColdFusion Server "dusts" a template, and anywhere it finds these "fingerprints", it says "Ah ha! I need to do something here." In this case, the server receives a request to display the value of the variable named "MyWorld". So, rather than show you the word "MyWorld", it will show you the value of the variable, which is "Hello World" in this case. Let's do another one -- this time we'll introduce two simple FUNCTIONS.
Now()- This function grabs the current date and time from the server, and formats them in a standard time-stamp manner.
DateFormat(date, 'mask')- Using this function, we will override the default formatting of the date created with
Now(), and tell ColdFusion how we want it formatted.
This line of code will take the current date and reformat it to something like 04/12/2003. The cool thing is that you can treat this whole glob of code as regular text, like so:
Hello, Today Is <CFOUTPUT>#DateFormat(Now(),'MM/DD/YYYY')#</CFOUTPUT>.
Using this code in this manner, you'll see:
Hello, Today is 04/12/2003
Add this code to your INDEX.CFM page and try it out. You can also add some font tags or other formatting HTML around this code to achieve your desired effect. For more uses and formatting options of the
DateFormat()function, consult the functions reference section at the end of this article. You will notice that we nested functions in this code sample.
ColdFusion allows you to combine or "nest" functions forever. There's no limit to the number of functions you can combine. Success with ColdFusion is based on two things:
- Know your code. Spend the cash to buy a current CFML Language Reference book and study it. It really is interesting reading.
- Practice. As with anything, practice makes perfect.
Note that in some cases you may want to display a pound sign to the user. To do this, you need to "escape the pound sign". This is done by placing two ## together with no information between them. ColdFusion will interpret this as a single character, not a variable to be processed. For example, if you use the
<CFOUTPUT>tag around a table, and in your HTML tags you try to designate a
BGCOLOR="#FFFFCC", ColdFusion will read this as the start of a process. To properly escape this you would enter
Lesson 2: Using ColdFusion to Display Database Contents Perhaps the biggest feature of ColdFusion is the amazingly simple way it interacts with databases. CFMX can tie into just about any database you can think of… Oracle, MS SQLServer, MySQL (my personal fave), MS Access, FileMaker, Sybase, Informix (my least favorite!) and more! To work with CFMX and databases, you need to understand two things. ODBC and SQL.
- ODBC stands for Open Database Connectivity, and is the basis on which ColdFusion connects to most standard databases.
- SQL or “See-Quill” is the basic language that’s used to talk to databases. It’s a simple language that can make or break you as a developer. I suggest picking up a copy of Learn SQL in 10 Minutes by Ben Forta. This lesson assumes that you don’t know SQL, though, so I’ll keep it simple.
First things first: we need a database! To save time, I’ve created a very simple database for you to download and use. It requires at least Microsoft Access 2000 — so make sure you have it before you continue. Now, we need to create a simple ODBC connection. This will require connecting to CFMX Administrator, the control panel that allows you to interact with the ColdFusion Application Server.
- Browse to 127.0.0.1:8500/cfide/administrator
- Enter your password. You should know this… if you installed the server properly. If you forget it, look at CFFAQ.com for details.
- In the left navigation, click the “Data Sources” link.
- In the Data Source Name field, enter “CFData” without the quotes.
- Open the dropdown list, select Microsoft Access and click ADD.
- Browse the server to the database, or type in the path to the file manually.
- Click SUBMIT.
- If you did everything right, CFMX will display a message saying that the Data source was updated successfully, and you’ll see “OK” next to your source in the list of connected data sources.
Now that you have an ODBC connection, let’s look at the database itself. This database is about as simple as possible, and contains just one table that holds a few records. In the real world, this rarely happens. If you’re unfamiliar with relational databases, Access is a good place to practice, but, a word to the wise: Access isn’t the best solution to your database needs. If you are looking at low traffic and minor data updates, then you’ll be fine with Access. If you are building a huge database against hundreds of thousands of records and/or expect high usage, consider trying MySQL… and if you can afford them trying SQLServer or Oracle. Our database in this case contains a few records in the table named INFO. If you don’t know what a database table is, think of it as a big spreadsheet that holds all your data. Inside this table are records comprised of data stored in columns. It’s really quite simple. This database contains the following columns:
NAME ADDRESS CITY STATE ZIP PHONE EMAIL NOTES ID
Note that the ID column is your
PRIMARY KEY. This is the standard way Access creates a unique identifier for each record in a database. Now, we’re going to use CFML to suck some of this data out onto the screen.
- Create a new folder under the CFMX Webroot, named LESSON2.
- In your text editor, create a new file and save it as ALLDATA.CFM
- Now, in that file, add this code between the BODY tags:
<CFQUERY DATASOURCE="CFdata" NAME="getall"> SELECT * FROM Info ORDER BY Name ASC </CFQUERY>
- Then below this code, add the following HTML:
<table align="center" border="1"> <CFOUTPUT QUERY="getall"> <tr> <td>#CURRENTROW#</td> <td>#NAME#</td> <td>#ADDRESS#<BR>#CITY# #STATE#, #ZIP#</td> <td>#PHONE#</td> <td>#EMAIL#</td> <td>#NOTES#</td> </tr> </CFOUTPUT> </table>
- Save the page and view it in your browser.
It’s not pretty yet — but it works! Let’s review what this code does. The
CFQUERYtag is the means by which CFML retrieves data from a database. The attributes we specified,
NAME, are required by CFMX. The
NAMEattribute of this tag is specified by you, and can be any word that’s easy to remember. Query names cannot contain spaces or punctuation. Between the opening and closing
CFQUERYtag is the SQL Query itself. This is not CFML, this is SQL, the database language. So just what did we tell the database to do? Let’s look at this in detail.
This tells the database to get records. The asterisk means all records. So In short, we’ve told the database to
Well, now that the database has been told to get all records, it follows that we need to tell it where to get them from. This line tells the database the name of the
TABLEfrom which we want to select the data. In this case, we want the data from our table, Info.
ORDER BY Name ASC
This last line is really just gravy. It tells the database that, now that we’ve selected all data from the Info table, we want it organized by the column
NAMEin ascending alphabetical order. If you wanted to sort the data by descending order, you’d use the abbreviation
What’s so great about CFML and SQL together, is that you can easily use CFML to augment your query to retrieve exactly the data you need… which brings us to the last part of this lesson.
Lesson 3: Using CFML to Search the Database In part two, we used CFML to dump the entire database out to the screen. This works fine for a small database, but in real life it’s rarely useful, and can cause some serious performance problems. The easiest solution is to give users the ability to search the database to find exactly what they need. With CFML this is a snap.
- Create a new file inside the lesson2 folder named INDEX.CFM
- Between the BODY tags of this document, add an HTML form like so:
<div align="center"> <form action="search.cfm" method="POST"> Search for:<input type="text" name="k"> <input type="submit" value="Find!"> </form> </div>
- Now create another new page named SEARCH.CFM
- Between the
BODYtags we need to deal with validating the submitted form. Add this code:
- Save the pages and try them out in your browser.
Now, let's review the code. There's a lot more this time so we'll take it in chunks. The INDEX.CFM page contains no tricks. It's just a simple HTML form. I named the text field "k" to stand for "keywords"...this is just how I do it. SEARCH.CFM contains a load of CFML you've probably never seen before. The first new tag you see is
<CFIF>. This is the standard method we use to deal with conditional processing in CFML. This tag has several variations. For full details, check the reference at the end of this article. Basically what this specific use does, is stop users who try to submit for search form without entering any search keywords. Conditional processing allows a developer to say "if the sky is blue do this. Otherwise do this or this". This lets you trap events and possible errors, and control them to do exactly what you need.
<CFIF len(FORM.k) IS 0>
len(FORM.k) IS 0" portion of the above tag uses the
LEN()function to determine the length of the submitted form field contents. In this case, if the length of the form field is zero, we will stop the page from processing.
This tag is the "otherwise" condition. So if a user submits proper search criteria, CFMX will continue to process the page. Let's take a closer look at that SQL. The first two lines should be familiar, but that last line might be new.
WHERE Name LIKE '%#FORM.k#%'
This is the
WHERE CLAUSEin SQL. It's used to tell the database exactly what data you want selected. The basic syntax is
WHERE ColumnName LIKE'something'. The "something", if surrounded by quotes, must be a
STRING VALUE-- a word or words. Without quotes, you tell the database to match on a number. In this case, we're letting ColdFusion fill in the blank with the form field value submitted by the user. Wildcards: as with many languages, SQL allows you to use wildcards to increase the power of a search. In the above code we use the percent symbol to denote a wildcard. Inside the percent signs we place the submitted form variable "k". Here are some examples:
%variable%' means CONTAINS the variable value
variable%' means START WITH the variable value and ends in anything
%variable' means ENDS WITH the variable value and starts with anything.
The next section of the results code that we need to examine is the next
CFIFblock. This code checks the
RECORDCOUNTof the query, and if it is not zero -- meaning the query returns anything larger than the number zero -- the page will process. Next is a section that states how many records were found that match. Note the way the variable is called:
FINDEM.RECORDCOUNT. This uses the query variable
RECORDCOUNT, and only displays it once. If you were to place this code inside a
CFOUTPUTthat contained the
QUERYattribute, the code would repeat for each record found! Not at all useful! Each ColdFusion query returns three automatic variables.
CURRENTROWis the actual numbering of each record. For instance, if your query returns 50 records
CURRENTROWwould number them 1-50.
RECORDCOUNTreturns as a number the amount of records your query found.
COLUMNLISTreturns a comma separated list of the columns in the table searched. So there you have it! The basics of ColdFusion and CFML. As you can see, it takes some work, but CFML is a simple and effective way to create any kind of Web application you can think of. Keep your eyes peeled for more on CF soon!
Tag and Function Reference
<CFOUTPUT></CFOUTPUT>Displays the output of a database query, variable or other operation. Syntax:
<cfoutput query = "query_name" group = "query_column" groupCaseSensitive = "Yes" or "No" startRow = "start_row" maxRows = "max_rows_output"> </cfoutput>
<CFSET>Defines a ColdFusion variable. Syntax:
<cfset variable_name = expression>
<CFQUERY></CFQUERY>Passes queries or SQL statements to a data source. Syntax:
<cfquery name = "query_name" dataSource = "ds_name" dbtype = "query" username = "username" password = "password" maxRows = "number" blockFactor = "blocksize" timeout = "seconds" cachedAfter = "date" cachedWithin = "timespan" Either of the following: debug = "Yes" or "No" or: debug SQL statement(s) > </cfquery>
<CFIF></CFIF>Creates simple and compound conditional statements in CFML. Tests an expression, variable, function return value, or string. Used, optionally, with the
<cfif expression> HTML and CFML tags <cfelseif expression> HTML and CFML tags <cfelse> HTML and CFML tags </cfif>
LEN()Determines the length of a string or binary object. Syntax:
Len(string or binary object)
NOW()Gets the current date and time of the computer running the ColdFusion server. The return value can be passed as a parameter to date functions. Syntax:
DATEFORMAT()Formats a date value. Supports dates in the U.S. date format. Syntax:
DateFormat("date" [, "mask" ])
Tag specifications taken from ColdFusion MX Language Reference Guide, Copyright Macromedia, Inc.