Arrays

ColdFusion arrays are objects that can store a whole bunch of variables. As I said, arrays are objects; therefore, you can even create properties for them. We won’t get into creating their additional properties simply because we won’t create their properties very often. The length of the array does not have to be specified when you are declaring the variable. You can just keep adding variables or elements to it. This makes them perfect for situations where you need to capture an idea, but don’t have to keep creating variable names and polluting the global namespace with worthless variables.

Adding Elements to an Array

Example
<cfset myVar = "meatloaf">
<cfset myArray = arrayNew(1)>
<cfset myArray[1] = "Pickles">
<cfset myArray[2] = "Meerkats">
<cfset myArray[3] = myVar>
<cfoutput>
    #myArray[1]# <br/>
    #myArray[2]# <br/>
    #myArray[3]# <br/>
</cfoutput>

If you have ever used an array, you will realize that they are really standard in ColdFusion. If you haven’t, then keep reading this paragraph. Our array’s name is myArray, which we create the array by using the <cfset myArray = arrayNew(1)>. You might be wondering what the 1 is for. All arrays in ColdFusion start with the index of one, which we specify here. Next, you see myArray[] with a number in those brackets. Those numbers are the order of elements in the array. So when we print our array using the <cfoutput> tags, we see that #myArray[1]# gives us “Pickles”. If you look, you can see that we already set that above in a <cfset> tag.

Array Functions

Adobe has all of the documentation for ColdFusion on their website if you ever need to reference it.ColdFusion FunctionsFor an array, I have broken down the important array functions for you below.

ArrayAppendArrayIsDefinedArrayNewArraySum
ArrayAvgArrayIsEmptyArrayPrependArraySwap
ArrayClearArrayLenArrayResize
ArrayDeleteAtArrayMaxArraySetIsArray
ArrayInsertAtArrayMinArraySortListToArray

With SQL

First off, you need to be able to write SQL queries before you work with them in ColdFusion. Once you are able to write them, it is just a matter of putting them in the right ColdFusion Tags, and adding the right arguments. The starting tag for queries is <cfquery> and the closing tag is </cfquery>. A few arguments can be added, but we will stick with the simple ones. First, your awesome query needs a name for later reference. You can use name=”” where your name variable will be within those quotes to set the query name in ColdFusion. Next, we need to know where to find the database. Now, I can’t tell you exactly how to do this. You need to figure out how to create a connection string to a database. It is somewhat complicated and varies based on what database you are wanting to use. You can use the power of Google to figure that out. Once you figure it out, set that equal to the variable myDatabase and we will just use that variable to reference our database.

Returning Data from a Database

Example
<cfoutput>
    <cfquery name="myQuery" datasource="#myDatabase#">
        SELECT column1, column2 
        FROM someTable
    </cfquery>
    <cfloop query="myQuery">
        #option_id# - #reason# <br/>
    </cfloop>
</cfoutput>

Notice how when I was using the <cfloop>, I return #myQuery.column1# and #myQuery.column2#, these are both column names in the someTable table.

Inserting Data into a Database

Now, I don’t want to destroy your database, so I am just going to show you an example for the INSERT. While not as dangerous as a DELETE, always try to be careful that you don’t insert a million junk rows. We are going to input some variables in our ColdFusion code into the database.

Example
<cfparam name="goodReason" default="" type="string">
<cfset goodReason = "Chasing Squirrels">
<cfoutput>
    <cfquery name="myQuery" datasource=" #myDatabase#">
        INSERT INTO someTable (column1)
        VALUES(<cfqueryparam value="#goodReason#" cfsqltype="CF_SQL_VARCHAR">)
    </cfquery>
</cfoutput>

Since you already know some SQL, you could tell the INSERT query was going to be a little different than the SELECT query. Normally, you will not have the <cfset goodReason = “Chasing Squirrels”> in the statement because it should be set somewhere else by the user input. Our <cfparam name=”goodReason” default=”” type=”string”> is searching for GET and POST data that might contain our variable goodReason, if it cannot find it then goodReason‘s value is set to “” (nothing). The type is important to help stop users from switching what it is supposed to be. While it isn’t that helpful with a string, consider if goodReason was supposed to be a number, but the user switched it to a string. Obviously, that wouldn’t be good for business. The same thing is happening down in the actual query. The <cfqueryparam value=”#goodReason#” cfsqltype=”CF_SQL_VARCHAR”> is the last line of defense against SQL injections attacks in ColdFusion. It makes sure that the value is what type of value we want it to be.

Deleting Data from a Database

I highly recommend that you back this data up somewhere else before deleting it or consider making a column in the database that is something like “isVisible”, where you could get the records. The idea would be that you would only show records that have isVisible set to 1, and the records set to 0 would show you past records so you don’t lose any data. But, if you must annihilate the data, we can cover that too. Again, I am not going to destroy our precious database, but I will show you an example.

Example
<cfparam name="goodReasonGoneWrong" default="" type="string">
<cfset goodReasonGoneWrong = "Chasing Squirrels">
<cfoutput>
    <cfquery name="myQuery" datasource=" #myDatabase#">
        DELETE FROM someTable
        WHERE column1 = <cfqueryparam value="#goodReasonGoneWrong#" cfsqltype="CF_SQL_VARCHAR">
    </cfquery>
</cfoutput>

Again, the <cfset goodReasonGoneWrong = “Chasing Squirrels”> will usually not be there. What is the point in setting a variable right before inserting it into a database? We would be better off just putting VALUES(‘Chasing Squirrels’) instead. Now that I have beaten that dead horse, you probably guessed that the DELETE query would also be different from the rest. We set the column column1 equal to our <cfqueryparam value=”#goodReasonGoneWrong#” cfsqltype=”CF_SQL_VARCHAR”> to escape SQL injection. So, this query actually deletes anything in our table that has ‘Chasing Squirrels’ in the column1 column.

Transferring Data

There are two primary ways to transfer data from page to page in ColdFusion. Embedding a variable in the url, or posting the data with a form are excellent ways to transfer data such as a variable from page to page.

Using Links to Transfer Variables

Links are very effective at this, but please try not to put more than 2 or 3 variables in a link. It is extremely tacky and everyone likes a nice clean url. Below are examples of how to use a link to transfer data.

Example
//Page 1
<a href="test.cfm?myVar=427">Loop Statement</a>
//end Page 1

//Page 2
<cfparam name="myVar" default="" type="integer">
<cfoutput>
    #myVar#
</cfoutput>

Pretty awesome, huh? You just transfer variable data through a link. ColdFusion is smart enough to understand where the page name ends and the url parameters begin.

The extremely important <cfparam> tag

Go ahead and type some numbers in the url after “myVar=”. If you tried being smart and typing in letters, you should now have an error. The type allowed for our variable was set in the <cfparam> tag. Basically, what happened here was that you put a variable in the url and the <cfparam> tag went looking for anything with the name of myVar to set its value too.There are like 20-30 actual types that the <cfparam> can hold, but here are some of the important ones.

  • boolean
  • integer
  • string
  • list

Of course, Adobe has an awesome tutorials on the <cfparam> tags. Just go to their website, and look it up in the “ColdFusion Tags” section.

Using Forms to Transfer Data

Forms can transfer data in two ways, through a GET or POST action.

GET Request

Example
<cfparam name="getTextBox" default="" type="String">
<cfoutput>
    <form action="ColdFusionTransferring.cfm" method="get">
        <input name="getTextBox" type="text" value="Type a string here..." onfocus="$(this).val('')"/>
        <input name="" type="submit" value="Submit" />
        You typed: #getTextBox#
    </form>
</cfoutput>

Notice how the url has the variable in it after you submit the form because the following POST Request will not. POST Requests are still inside the HTTP Request, but they are not displayed in the url. You can use FireFox’s FireBug or Chrome Developer Tools to see these requests and the post values.

POST Request

Example
<cfparam name="postTextBox" default="" type="String">
<cfoutput>
    <form action="ColdFusionTransferring.cfm" method="POST">
        <input name="postTextBox" type="text" value="Type a string here..." onfocus="$(this).val('')"/>
        <input name="" type="submit" value="Submit" />
        You typed: #postTextBox#
    </form>
</cfoutput>

If you clicked submit on the GET Request and then clicked submit on the POST Request right after, you will notice that the GET Request is actually cleared from the url and doesn’t appear in page. This is because every time we are clicking submit we are sending the forms contents and putting them into temporary variables for the next page. So, when we did the POST request after the GET Request, we lost our GET variables because we weren’t sending them to the next page.

GET/POST Etiquette

So, why don’t we just use GET Requests for everything? I mean it would have the variables up in the url where we could see them. It would help with debugging. While that is great, GET Requests make the url look tacky, and a url can only be so long. That means if you had enough variables in your GET Request to surpass the url length limit, you wouldn’t actually get all of the variables. So, please try to stick with POST requests unless you need the user to be able to show other user’s that specific state through sharing a link. It is recommended that POST Requests are when you want to modify data, and GET Requests are to show data.

Try and Catch Statement

ColdFusion provides a try and catch statement to deal with error handling. Basically, a try and catch statement attempts some code. If the code fails, ColdFusion will do whatever is in the exception to try to handle it without breaking and spitting out an error message to the screen. Of course, many different types of exceptions can occur, which should sometimes be handled in a different manner than the others. Let’s take a look at the general syntax of a try and catch statement in ColdFusion.

Example
<cftry>

  <!—Code tried —>
  <cfcatch type=”Exception_Type”>

    <!—Code executed when the code above fails—>
  </cfcatch>
</cftry>

So, we can see that it isn’t very complicated. You simply have a try and a catch. In the try, you attempt the code that might fail. The catch code is only triggered when that happens. The idea for the catch code is to handle the error and not just to stop ColdFusion from showing an error message. You actually want to correct something in the catch statement.

When to use a try/catch statement

Some people don’t want to use try/catch. They think that if there is a chance the code might not work, they shouldn’t use the code at all. So, what are a couple of examples of why this would be useful? Let’s say you have some code that updates a database with extremely important information for your manager. So, if that code fails your manager would never get any of the information derived from that code. However, if you would have used a try and catch statement, you could have made ColdFusion send an email with the information whenever it failed. This would let your manager have information that he wouldn’t have without this powerful little function. You can also use try and catch to improve the exception reporting from ColdFusion. A custom message from the web developer is usually better than a default error message.

Introduction

Coldfusion is written right along side your HTML code. ColdFusion is a little different from other server side languages because it is written almost entirely <tags>, just remember that when you are programming. While ColdFusion is very relaxed when it comes to syntax, it is import to maintain a proper variable naming scheme and to have consistency throughout your pages. Well, that was a quick introduction, now let’s’ write our first ColdFusion script! To create your first ever ColdFusion file, give it a name followed by “.cfm” This is the file extension for ColdFusion. What we are going to do here is to write something to the document. If you ever want ColdFusion to output something, you must have the output in the <cfoutput> and </cfoutput> tags.

Example
<html>
    <body>
        <cfoutput>
            ColdFusion Wrote me
        </cfoutput>
    </body>
</html>
Result ColdFusion Wrote me

As you can see, it is pretty easy. I would recommend breaking your pages into a logic section where you put all of your important code and an output section wrapped with <cfoutput> and ending it with </cfoutput> that way you wouldn’t have to keep putting it around each new thing you want to write to the document. Separating your code into logic and outputting (views) is a great practice. Personally, I recommend them being two different pages and using classes, but we won’t dive into OOP in the ColdFusion tutorial. Most of it is written using a procedural coding practice anyway.The above example was how to output data to the DOM, but ColdFusion has different ways to specify outputting html and to output actual ColdFusion values. You will see how to do this in variables.