oldFusion is a relatively simple, tag-based, programming language used mainly for Internet applications such as shopping carts and email systems. ColdFusion software runs on the server that hosts a Web site, processing the ColdFusion sections of documents that may, and often do, contain regular HTML code as well. If that is confusing, read on. It will come to you.
ASP Code:<% set conn = Server.CreateObject("ADODB.Connection") conn.open "contacts" conn.Execute("DELETE FROM contacts WHERE id="+ id); conn.close%>
DELETE FROM contacts WHERE id = #id#
Both of these examples delete a user from the “users” table in a “contacts” database where the value in the id column matches a number sent from a form. The CFML is both easier for beginners to read and there is less of it. ColdFusion applications can be developed very quickly and are easy to troubleshoot and fix. The error messages sent by ColdFusion when the code doesn’t work tend to be specific, which helps reduce development time.
How ColdFusion Works
When you visit a Web site that uses ColdFusion, you may notice a .CFM extension in the address, such as www.wordevelopment.com/BOOYA.CFM. The “BOOYA.CFM” file contains code (ColdFusion Markup Language, or CFML) that resides and runs on a Web server. The output from the CFM file is usually HTML, which the server returns to the users Web browser. Even though you may see the .CFM extension in the address of a Web site when you visit it, no CFML is sent to your browser; instead, the .CFM extension says to the server Yo server, get ColdFusion over here to take a look at this. The server won’t process CFML in a file with an .HTM extension unless you have configured your server to do so. If you are new to ColdFusion, remember to save your files with a .CFM extension as you test the examples on the next few pages.
Introduction to CFML
Like HTML, CFML code uses tags. For example:
All CFML tags start with “CF”; HTML tags do not. The example above contains both normal HTML tags (HTML and BODY), and one ColdFusion tag, CFSET. The CFSET tag sets the value of the variable “name” to “Reginald.”
Author Note: The capitalization I use in these examples is optional, though it helps to separate the tags from regular text.
A quick word about data types: When dealing with values such as “Reginald” or “235 Main Street”, you must use quotation marks around the text. Text values are called strings. Strings are basically a set of varied characters that may or may not include numbers, letters and symbols. This paragraph is one long string. In contrast, when you’re using a number (not a representation of a number in text) such as 34 or 67.29494, you don’t use quotes. If you’re ever at a programming party, use the term “string” instead of “text” to refer to a series of characters and you will look like you know what you are talking about.
The big advantage of code-driven Web documents is that you can programmatically insert values in the server’s response. In other words, CFML makes Web responses “dynamic,” they can change depending on the user, the situation, the time of day, the requestor’s IP address, or any other criteria you like. In contrast, when a user requests a pure HTML file, the response is “static”?that is, the response doesn’t change unless the contents of the requested file changes.
Here’s a simple example. Suppose you want to display a variable’s value in the body of a document. You will need to wrap the variable with CFOUTPUT tags, and put pound signs immediately around the variable.
When the server processes the page, it replaces the CFOUTPUT tag and the #name# variable with the value of the #name# variable?in other words, the name “Reginald” will show up on the page.
Even though the value of the variable “name” is a string, you don’t need to put quotes around the variable #name# because ColdFusion is just printing the value to the page.
The CFOUTPUT tag tells the server to insert a variable’s value in place of any variables in the format #variable_name#. If that didn’t happen, ColdFusion would ignore the pound signs and the variables values and your browser would see #name# and print it on the page.
So, outputting variable values in ColdFusion is easy enough, but what about something a little more intense?Suppose you want to have different responses for different names. Maybe, if the name variable’s value is “Reginald,” you want to greet him politely. But if the value is not Reginald, then you want to scold the intruder using discouraging words.To test the variable value, you use the CFIF tag. Take a look at the example below:
Hello Reginald, it is very nice to see you. Wont you sit down and have some tea with me? You are not Reginald. I don't know how you got in here, but youd better leave.
The preceding example compares the value of the variable “name” to Reginald to see if they are equal. If so, the server returns the text immediately following the CFIF tag; otherwise the server returns the text following the CFELSE tag intended for non-Reginald users (anything ELSE). Finally, the closing tag stops the processing. The CFELSE tag is a continuation of the CFIF tag, and does not have to be closed.
Note the EQ in the CFIF opening tag,
You’ve seen a simple, if not very practical example of conditionally displaying variable values. Now that you know how to compare and display values, let’s move on to forms, and do something a little more useful.
ColdFusion and Forms
When creating a Web application, you often need information from the users who visit your site. Maybe you need their contact information to sign them up for a newsletter or to deliver products. Maybe you need them to provide feedback about the site itself.
Here’s a real-life, practical example that asks people to select their favorite color then displays their name in that color so they can print it out to use as a reference on a later date (in case of amnesia or stroke).
First you need to make a page called fav_color_form.cfm. The page will contain a form that collects the user’s name and favorite color using a text input field and a dropdown list.
In a browser, the preceding code appears something look like Figure 1.
|Figure 1: This sample form collects the user’s name and favorite color using a text input field and a dropdown list.|
Note that the text field is named “name” and the select list is named “color.” When the user submits the form, ColdFusion has access to the variables “name” and “color,” which will contain the values selected by the user.
Now, you need to create the file that will process the data sent by the form and output the user’s name in their favorite color. In the FORM tag above, the action attribute value controls where the form submits the data; the sample form will submit its data to the file color_display.cfm, shown below:
You need to go back and select a color. You must be a bad person and we don't want to deal with your kind. Your name is #name# Your name is #name# Your name is #name#
The first CFIF tag checks to see if the color value is unspecified. It checks to see if the variable “color” is equal to “select,” the default value. If so, the page returns the message “You need to go back and select a color.” The subsequent CFIF tags deal with each possible color value.
Writing a CFIF for every possible entry of “color” gets the job done, but there’s a better way. Rather than checking for every color, you can just return text rendered in the color sent by the form, using the user-selected color as the value of the color attribute of the FONT tag. You just need to ensure that the value of the color variable “color” is a color, not none and not the default value, select.
Here’s the modified code:
You need to go back and select a color. You must be a bad person and we don't want to deal with your kind.
Your name is #name#
You can print this page to use as a reference in case of amnesia or stroke.
There’s a new tag in the preceding code?CFELSEIF. It’s useful in this example because the code needs to test whether the color variable is equal to “select” and “none.” If both those tests fail, ColdFusion displays the code after the CFELSE tag. CFELSEIF is a continuation of the CFIF tag and does not have to be closed.
You can display the values of variables using CFML anywhere on the page, including inside HTML tags. For example, you can insert the color the user selects in the form directly into the tag as the “color” attributes value. This shortcut streamlines the code, which is good because the server does not have to process as many lines nor do you have to type them. If you fill out the form and enter “joe” in the name field and select blue as your favorite color, the server returns the following HTML to your browser:
Your name is joe
You can print this page to use as a reference in case of amnesia or stroke.
You can test the Favorite Color Recovery System here.
ColdFusion and Databases
ColdFusion works wonderfully with databases, which are an essential element of dynamic, interactive web sites. In this section, you’ll use the favorite color example from the last section and further streamline the “Favorite Color Recovery System.”
Suppose you want to store a user’s favorite color on your Web site and be able to retrieve it later, simply by having users enter their name. To do that, you’ll need a database designed to store user names and favorite colors, for example, in a table called “users.”
The sample code uses an Access database, but you can use any database in a similar manner. If you want to try the Access version, you can download it here.
Adding Records To a Database
Databases can have many tables. A record is a row or entry in a table. The columns specify the names and types of data the table can contain, and the rows contain the specific values. Figure 2 shows the structure of the sample “users” table:
|Figure 2: This shows the structure of the sample “users” table.|
To add records to a database, you need a form handler which will receive the contents of the form and enter the data into the database. Change the the form in fav_color_form.cfm so it submits to a file called db_user_add.cfm (the “db” stands for “Database”) by modifying the form tag’s action attribute value.
After doing that, the form will send the variables “name” and “color” to the db_user_add.cfm file. That file should retrieve and insert the values into the “users” table using CFQUERY. A query is a question or command sent to a database. Queries are often used to answer questions about data such as “Give me all the names of people who say red is their favorite color.” The database would then send the names of the people whose favorite color is listed as red.
You use the CFML tag CFQUERY to both get data from (retrieve) and send data to (insert, update), the database. CFQUERY is “the tag of database conversation.”
The CFQUERY tag has a name attribute, where you name the query whatever you like. In my personal naming scheme, all query names start with “Q” so I can recognize them in the code more easily.
The CFQUERY also has a datasource attribute where you specify which database to use. The sample code uses a DSN (Data Source Name) called “FC” which you set up on the server to point to the Access sample database. A DSN is basically a shortcut to the database, just as the variable “color” may represent the value “blue.”
INSERT INTO users (name, color) VALUES ('#name#', '#color#')
User added successfully.
Oh no! What’s all that code between the CFQUERY tags??!? That is SQL, the language of databases. SQL has its own syntax that’s independent from CFML. But don’t worry, SQL is pretty straightforward. If you haven’t seen SQL before, you can get a good introduction here.In the preceding example, the SQL statement means: “Insert the following values into the table ‘users,’ in the columns ‘name’ and ‘color’.” Then the values sent from the form are listed in the same order as the column names. Intense, yet straightforward.
Now what if, by some amazing coincidence, there are two people using the system who have the same name, for example “Reginald”? Before inserting a new record, you need to ask the database if any users already exist whose name is “Reginald.” If no such users exist (the query doesn’t return any information), you can go ahead and add Reginald.
Select * FROM users WHERE name = '#name#' That name is taken, please go back and enter a different name. INSERT INTO users (name, color) VALUES ('#name#', '#color#')User added successfully.
The preceding code first queries the database for all the rows (the “*” means “all columns”) where the value of the name column is the same as the name value sent by the form. In SQL statements, you need quotes around strings. The CFQuery returns any rows matching the query as an object, with the same name as the query?qget_similar_user in this case. That object has a property called “RecordCount” which contains the number of rows returned from the database. In CFML, you access an object’s property values with “dot syntax”?using the name of the object, a dot, or period, and then the name of the property, as in qget_similar_user.RecordCount. So the code checks the “RecordCount” property to see if the query returned any rows. The GT is an operator meaning “greater-than.” If any records were sent (more than 0), the code tells the user to go back and enter a different name. If the name is not taken, after the CFELSE tag, the code uses another CFQUERY to insert the name and favorite color into the users table.
Creating a Login System
Now that you can save a user’s name and favorite color in the database, you can create a login page so that existing users can enter only their name to retrieve their favorite color.
Here’s a simple form with one entry field:
|Figure 3: A simple login page.|
In a browser, the above code looks like Figure 3.
This form sends a name to the sample “get_color.cfm” file. That file asks the database which color is associated with the user’s name and prints it on the page. Suppose Reginald signs in and already has red listed in the database as his favorite color.
SELECT color FROM users WHERE name = '#name#'
NO RECORDS FOUND
RESULTS:#name#'s favorite color is #color#.
The SQL statement in the CFQUERY tag asks: “From the table users, give me the color where the user’s name is Reginald.” Next, a CFIF tag tests to see if the query returned any results. Because the name “Reginald” returns a row from the database, the CFIF tag fails, and the code executes the CFELSE tag, which contains a CFOUPUT tag which substitutes “Reginald” for the #name# variable and “red” for the #color# variable and sends the resulting HTML back to the browser. The code has access to the values because the CFOUTPUT tag specifies a query name (the qget_color query), so the value sent from the database for “color” is readily available to be displayed in between the CFOUTPUT tags.You can test the streamlined, new and improved, database-driven Favorite Color Recovery System here.
The Next Step
You’ve probably seen enough to continue building this application on your own. Your mission, should you choose to accept it, is to set up a page that deletes users and a page that updates a users color. The following SQL code should help.
The SQL statement for deleting records:
DELETE FROM users WHERE name = #name#
The SQL statement for updating the color in a record:
UPDATE users SET color = #color#WHERE name = #name#
Most applications aren't complete without some reporting. In this section, you'll create a reporting page that displays the contents of the Favorite Color Recovery System sample application. To do that, you need to create a query that selects all the records from the database, and then add some CFML to display the results in an HTML table.
The SQL is simple:
SELECT * FROM users
Again, the asterisk in the SQL means "all columns."
This query is slightly different from the other queries in this article because, rather than one record, it returns a series of records, known as an array. An array is basically a list of items, for example:1,2,5,7,9,15
You can use the CFOUTPUT tag to process each item in an array returned from a database. For each record in the database returned, ColdFusion runs the code within the CFOUTPUT tag. This iterative process is called looping.
SELECT * FROM users
The preceding code displays every record in the database showing each users name and color.
Another form of reporting is visual. For example, you can display a bar graph of the entries in the database. To get the rows that have blue as the value in the column "color," we can use the SQL:
SELECT * FROM users WHERE color = blue
If you run a query for each color, you can display colored images that are as many pixels wide as the number of rows returned for each query. The images in Figure 4 represent the number of users who have blue, green, red, or none listed as their favorite color.
|Figure 4: The images represent the number of users who have blue, green, red or none listed as their favorite color.|
SELECT * FROM users WHERE color = 'blue' SELECT * FROM users WHERE color = 'red' SELECT * FROM users WHERE color = 'green' SELECT * FROM users WHERE color = 'none'
The number of records for each color will determine the size of each image, resulting in a bar graph.
Because you are referring to several queries, you don't want to specify a query in the CFOUTPUT tag itself. You can refer to the RecordCount of each query specifically. See the bar graph page in action here.
ColdFusion is a powerful Web application programming language. Development time is often speedy and debugging is relatively simple. ColdFusion is a great gateway language for those who are new to the world of programming.