Switch Statement

As long as you are able to grasp the idea that all of ColdFusion is in tags and understand how to use an if statement, switch statements aren’t too difficult to understand. The expression must be in the output tags, ## and in quotes, of course. The <cfcase> follow the expression, but they don’t need to output a variable so the ## should not be here unless you planning on putting a variable in the numbers place. Just try to think of a switch statement as one really really long or short (depending on how many cases you make) if statement. That is one long if statement with a lot of else ifs. Let’s go to an example.

Example
<cfoutput>
    <cfset x = 3>
    <cfswitch expression="#x#">
        <cfcase value="1">
            My value is 1 <br/>
        </cfcase>
        <cfcase value="2">
            My value is 2 <br/>
        </cfcase>
        <cfcase value="3">
            My value is 3 <br/>
        </cfcase>
        <cfcase value="4">
            My value is 4 <br/>
        </cfcase>
    </cfswitch>
</cfoutput>
Result

My value is 3

Let’s break the switch statement down. We have the switch statement put in one big <cfoutput> because we are lazy and that is what lazy people do. Then, we set our variable x equal to 3. After that, we finally come to our switch statement. The <cfswitch expression=”#x#”> is where we define what variable we are going to check the cases (or ifs) against. Using our variable x, we run through the first case <cfcase value = “1”>, which is simply asking is our variable x equal to one? If it is, do everything before the closing </cfcase>. If not, skip the current <cfcase> and check the next one. So, we fail the first few cases and come to the <cfcase value=”3″>. We meet the condition and so we output “My value is 4 <br />”. Finally, we exit the switch statement. Tutorial mastered!

Functions

In ColdFusion, functions are probably the best way you can make your code readable, and keep the scope at the level you want. Remember to add a useful comment before each function. It also prevents you from using variables with the same name (not that you should have variables with the same name). In ColdFusion variables declared inside the function are local variables, which means they cannot be called outside the function. Functions do absolutely nothing until they are called. Generally, you should try to put your functions above your outputting code to separate your logic from your output (views). Let’s go through one together.

Example
<cffunction name="addingFunction" access="public" returnType="numeric">
    <cfargument name="firstNumber" type="numeric" required="true">
    <cfargument name="secondNumber" type="numeric" required="true">
    <cfset var sumOfThem = arguments.firstNumber + arguments.secondNumber>
    <cfreturn sumOfThem>
</cffunction>
<cfoutput>
    #addingFunction(2,3)#
</cfoutput>

The name=”addingFunction” sets the name of the function so we can call it later. The access sets the scope of the function, and returnType just specifies what type of value you will be returning. On to the arguments, we can see that there are two <cfargument> tags (With no closing tag). The arguments both have a name, a type, and a required attribute. You can probably guess what each of them do. The name is just the name of the argument that you can call later in the function. The type attribute is very important because ColdFusion gets grumpy if you pass in the wrong variable type, which makes a lot of sense. No one wants a function trying to parse random variables. You should know what argument types your function takes if you are going to be using it. Finally, the required attribute lets ColdFusion know if it is an optional parameter.

Next, we do the actual action of the function. We set a variable called sumOfThem equal to our first argument, arguments.firstNumber, plus our second argument, arguments.secondNumber. Pay attention to the fact that we used var before our variable name. We are doing this so that we create a new variable even if one exists outside of this function. Finally, we use the <cfreturn> tag to return our result to where ever we called the function. Notice how we add the arguments. before the actual argument name. This is just so we don’t use another variable floating around. Always try to control your variable names when you are getting their value. A little extra code won’t kill you and will prevent some future errors.

Let’s walk through the function. #addingFunction(2,3)# calls the function and passes in 2 as the first argument. So, arguments.firstNumber now equals 2. Since we also passed 3 into the function, the arguments.secondNumber now equals 3. After we have set the arguments in the function, we add them when we set the sumOfThem variable. Finally, we return that variable, and the <cfoutput> tags writes out 5 because our function #addingFuction(2,3)# returned 5.

Functions are awesome, use them.

Loop Statements

In ColdFusion, loops are also quite a bit different from other languages in that their arguments look more like html attributes. However, I must first start out that telling you ColdFusion loops are one of my favorite things about ColdFusion. You can literally loop through anything in about any way that you want. You can loop through query results by just giving the loop the query name and a variable to increment. Alternatively, you can simply loop within ranges by giving ColdFusion the increment variable, starting point, ending point, and an index. Granted it isn’t as cool as ColdFusion being able to query a query (we will get to this), but the flexibility of loops give ColdFusion a step up over other languages.

Example
<cfoutput>
    <cfloop index="x" from="1" to="10" step="1">
        #x# <br/>
    </cfloop>
</cfoutput>

The index argument is the variable you want to be involved in the loop. Usually, we will increment this variable by the step argument until we have ColdFusion return all the results that we wanted. from is your beginning value of x, and to is the finally result of x. The last argument below is the step, which is by how much do we want to increment the index.

Looping Query Results

Looping query results requires that you already know how to use ColdFusion to get results from an SQL server. What you need to do is to run a query first. Then that query will be an object that you can loop through. You just need to provide the query name and then you need some way to use each iteration to output a different record of the query. You can simply use an incrementing variable that can be defined in the initial loop statement. It is best to discuss this when we have an actual query to run.

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 Functions For an array, I have broken down the important array functions for you below.

ArrayAppend ArrayIsDefined ArrayNew ArraySum
ArrayAvg ArrayIsEmpty ArrayPrepend ArraySwap
ArrayClear ArrayLen ArrayResize ArrayToList
ArrayDeleteAt ArrayMax ArraySet IsArray
ArrayInsertAt ArrayMin ArraySort ListToArray

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.