coldfusion #coldfusion Table of Contents About Chapter 1: Getting started with coldfusion Remarks Versions Examples Installation or Setup Linux (Ubuntu) Installation Lucee (Open Source) ColdFusion / CFML Interpretor Nginx Adobe (Closed Source) ColdFusion / CFML Interpretor Nginx Hello World Chapter 2: CFLOOP How-To Remarks Examples Looping through a collection using CFML tags. Looping through a collection using CFSCRIPT. Index Parameters Basic index loop Increase step to 2 Decrement step by 1 CFLoop in a Function ColdFusion 11 through current Condition Tag syntax Parameters Generated HTML 1 2 2 2 3 3 3 3 3 3 4 4 4 5 7 7 7 7 7 7 7 8 8 9 9 10 10 10 10 10 CFScript Previous to ColdFusion 8 ColdFusion 8 through current ColdFusion 11 through current Generated HTML Date or time range Query Parameters Example query Tag syntax Generated HTML Limiting output to specific rows Grouping Output CFScript ColdFusion 6 (MX) though current ColdFusion 8 though current ColdFusion 10 though current ColdFusion 11 though current List Tag syntax Parameters Generated HTML CFScript Previous to ColdFusion 8 ColdFusion 8 through current ColdFusion 9 through current ColdFusion 11 through current Generated HTML Array Tag syntax ColdFusion 8 through current 10 11 11 11 11 11 11 11 12 12 12 13 13 14 15 15 15 15 16 16 16 16 16 16 17 17 17 17 17 17 17 Parameters Generated HTML ColdFusion 2016 through current Parameters Generated HTML CFScript Previous to ColdFusion 8 ColdFusion 8 through current ColdFusion 9 through current ColdFusion 11 through current Generated HTML File Structure Tag syntax Parameters Using Structure Functions Implicit Structure Syntax Generated HTML CFScript Output the structure's keys Generated HTML Output the value of the structure's keys Using Structure Functions Implicit Structure Syntax ColdFusion 11 through current Generated HTML Index Loop Conditional Loop Query Loop List Loop File Loop COM Collection/Structure Loops 18 18 18 18 19 19 19 19 19 19 19 20 20 20 20 20 20 21 21 21 21 21 21 21 22 22 22 22 22 23 23 23 Chapter 3: cfquery Parameters Examples Using cfquery within a Function Query of Query Function Calls User.cfc Chapter 4: ColdFusion Arrays Syntax Parameters Remarks Examples Creating Arrays Creating arrays explicitly using ArrayNew() History Declaration Using ArrayAppend() Creating 1-D Array Implicitly Create 2-D Array Implicitly Array in CFScript Similarly, for 2 Dimension Array: General information Chapter 5: Creating REST APIs in coldfusion Introduction Examples Creating backend The interface Chapter 6: Database Queries Examples Working with databases Basic Example 24 24 24 24 24 24 24 26 26 26 26 26 26 26 26 26 27 28 29 30 31 31 32 32 32 32 32 33 33 33 33 Authentication Cached Queries Limiting the Number of Records Returned Timeouts Chapter 7: How to invoke a private method dynamically Remarks Examples CFML CFSCRIPT (CF10+) Chapter 8: Scopes in Coldfusion Introduction Examples Request Scopes Global Scopes Components and functions Custom tags Common scopes Overview Chapter 9: Variables Parameters Examples Using cfset Using cfparam Checking if a Variable Exists Setting a variable scope Chapter 10: Working with RegExp Replace callbacks Introduction Parameters Remarks Examples User defined REReplaceCallback function Using REReplaceCallback function 34 34 35 35 36 36 36 36 36 37 37 37 37 37 37 37 38 38 39 39 39 39 39 40 40 42 42 42 42 42 43 43 Credits 44 About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: coldfusion It is an unofficial and free coldfusion ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official coldfusion. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to info@zzzprojects.com https://riptutorial.com/ 1 Chapter 1: Getting started with coldfusion Remarks This section provides an overview of what coldfusion is, and why a developer might want to use it. It should also mention any large subjects within coldfusion, and link out to the related topics. Since the Documentation for coldfusion is new, you may need to create initial versions of those related topics. Versions Version Release Date Cold Fusion version 1.0 1995-07-02 Cold Fusion version 1.5 1996-01-01 Cold Fusion version 2.0 1996-10-01 Cold Fusion version 3.0 1997-06-01 Cold Fusion version 3.1 1998-01-01 ColdFusion version 4.0 1998-11-01 ColdFusion version 4.5.1 1999-11-01 ColdFusion version 5.0 2001-06-01 ColdFusion MX version 6.0 2002-05-01 ColdFusion MX version 6.1 2003-07-01 ColdFusion MX 7 2005-02-07 ColdFusion 8 ColdFusion 9 2007-07-30 2009-10-05 ColdFusion 10 2012-05-15 ColdFusion 11 2014-04-29 ColdFusion 2016 2016-02-16 https://riptutorial.com/ 2 Examples Installation or Setup Linux (Ubuntu) Installation Lucee (Open Source) ColdFusion / CFML Interpretor Download the appropriate file from their site (http://lucee.org/downloads.html) and execute their installer wget http://cdn.lucee.org/downloader.cfm/id/155/file/lucee-5.0.0.252-pl0-linux-x64- installer.run sudo chmod +x lucee-5.0.0.252-pl0-linux-x64-installer.run sudo ./lucee-5.0.0.252-pl0-linux-x64-installer.run Step through installer. Nginx Install Nginx on your server sudo apt-get install nginx Edit your /etc/nginx/sites-available/default server { listen 80; server_name _; root /opt/lucee/tomcat/webapps/ROOT; index index.cfm index.html index.htm; #Lucee Admin should always proxy to Lucee location /lucee { include lucee.conf; } #Pretty URLs location / { try_files $uri /index.cfm$uri?$is_args$args; include lucee.conf; } location ~ \.cfm { include lucee.conf; } https://riptutorial.com/ 3 location ~ \.cfc { include lucee.conf; } } Edit /etc/nginx/lucee.conf proxy_pass http://127.0.0.1:8888; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; Reload nginx sudo service nginx reload Access the Lucee Server admin here: 127.0.0.1/lucee/admin/server.cfm or 127.0.0.1:8888/lucee/admin/server.cfm Your root web directory lives here: /opt/lucee/tomcat/webapps/ROOT Adobe (Closed Source) ColdFusion / CFML Interpretor Download the appropriate file from their site ( https://www.adobe.com/products/coldfusion/download-trial/try.html) and execute their installer wget /ColdFusion_2016_WWEJ_linux64.bin sudo chmod +x ColdFusion_2016_WWEJ_linux64.bin sudo ./ColdFusion_2016_WWEJ_linux64.bin Step through installer. Make sure you select the internal web server (port 8500) Nginx Install Nginx on your server sudo apt-get install nginx https://riptutorial.com/ 4 Edit your /etc/nginx/sites-available/default server { listen 80; server_name _; root /opt/coldfusion2016/cfusion/wwwroot; index index.cfm index.html index.htm; location / { try_files $uri $uri/ =404; } location ^~ /CFIDE/administrator { deny all; } location ~* \.(cfm|cfml|cfc|html)$ { include /etc/nginx/conf/dc_tomcat_connector.conf; } location ^~ /rest { include tomcatconf; } } Edit /etc/nginx/tomcat.conf proxy_pass http://127.0.0.1:8500; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $http_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; Reload nginx sudo service nginx reload Access the Adobe ColdFusion Server admin here: 127.0.0.1:8500/CFIDE/administrator/index.cfm Your root web directory lives here: /opt/coldfusion2016/cfusion/wwwroot Hello World File: test.cfm Tag Implementation https://riptutorial.com/ 5 Hello World! CFScript Implementation writeOutput("Hello World!"); Read Getting started with coldfusion online: https://riptutorial.com/coldfusion/topic/913/getting- started-with-coldfusion https://riptutorial.com/ 6 Chapter 2: CFLOOP How-To Remarks Big thanks to • • Pete Freitag for his CFScript Cheat Sheet Adam Cameron for CF 11: CFLOOP in CFScript is Very Broken (and it still is in CF 2016). Examples Looping through a collection using CFML tags. Key : #attribute#, Value : #attributes[attribute]# Looping through a collection using CFSCRIPT. /*define collection*/ attributes = { "name": "Sales", "type": "text", "value": "Connection" }; for(attribute in attributes){ /* attribute variable will contain the key name of each key value pair in loop */ WriteOutput('Key : ' & attribute & ', Value : ' & attributes[attribute] & '
'); }
Index Parameters https://riptutorial.com/ 7 Attribute Required Type Default Description index true string Variable name for the loop's index. Defaults to the variables scope. from to true true numeric numeric Starting value for the index. Ending value for the index. step false numeric 1 Value by which to increase or decrease the index per iteration. Basic index loop Final value of x is 10.
  • #x#
  • for (x = 1; x <= 10; x++) { writeOutput('
  • ' & x & '
  • '); }
    - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 Increase step to 2 Final value of x is 11.
  • #x#
  • for (x = 1; x <= 10; x += 2) { https://riptutorial.com/ 8 writeOutput('
  • ' & x & '
  • '); }
    - 1 - 3 - 5 - 7 - 9 Decrement step by 1 Final value of x is 0.
  • #x#
  • for (x = 10; x > 0; x--) { writeOutput('
  • ' & x & '
  • '); }
    - 10 - 9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 CFLoop in a Function Make sure to var or local scope the index inside a function. Foo() returns 11. https://riptutorial.com/ 9 ColdFusion 11 through current The cfscript function cfloop has no support for index as a stand alone counter mechanism. Condition Tag syntax Parameters Attribute Required Type Default Description Condition that manages the loop. Cannot contain math symbols like <, > or =. Must use ColdFusion text implementations like less than, lt, greater than , gt, equals or eq. condition true string Final value of x is 5.
  • #x#
  • Generated HTML This will also have a line break between each line of HTML.
  • 1
  • 2
  • 3
  • 4
  • 5
  • CFScript https://riptutorial.com/ 10 Previous to ColdFusion 8 x = 0; while (x LT 5) { x = x + 1; writeOutput('
  • ' & x & '
  • '); }
    ColdFusion 8 through current x = 0; while (x LT 5) { x = x++; writeOutput('
  • ' & x & '
  • '); }
    ColdFusion 11 through current The cfscript function cfloop has no support for condition. Generated HTML Notice that the cfscript output is all on one line.
  • one
  • two
  • three
  • four
  • Date or time range Example for date or time range. Query Consider the table dbo.state_zip, which contains the columns city, statecode and zipcode and has over 80,000 records. Parameters Attribute Required Type Default Description query true string The variable name of a query object. startrow false numeric The starting row index of the query object. https://riptutorial.com/ 11 Attribute Required Type Default Description endrow false numeric The ending row index of the query object. group false string The query column name on which to group records. Example query SELECT city, stateCode, zipCode FROM dbo.state_zip Tag syntax Using the query object geo as the source for cfloop. Since the table dbo.state_zip has so many records, the HTML generated will take quite some time. This example shows only the first 20 records' worth of HTML.
    • #geo.city# | #geo.stateCode# | #geo.zipCode#
    Generated HTML
    • 100 PALMS | CA | 92274
    • 1000 PALMS | CA | 92276
    • 12 MILE | IN | 46988
    • 1ST NATIONAL BANK OF OMAHA | NE | 68197
    • 29 PALMS | CA | 92277
    • 29 PALMS | CA | 92278
    • 3 STATE FARM PLAZA | IL | 61710
    • 3 STATE FARM PLAZA | IL | 61791
    • 30TH STREET | PA | 19104
    • 3M CORP | MN | 55144
    • 65TH INFANTRY | PR | 00923
    • 65TH INFANTRY | PR | 00924
    • 65TH INFANTRY | PR | 00929
    • 65TH INFANTRY | PR | 00936
    • 7 CORNERS | VA | 22044
    • 88 | KY | 42130
    • 9 MILE POINT | LA | 70094
    • A A R P INS | PA | 19187
    • A A R P PHARMACY | CT | 06167
    • https://riptutorial.com/ 12
    • A H MCCOY FEDERAL BLDG | MS | 39269
    Limiting output to specific rows To limit the query's output to a specific range of rows, specify startrow and endrow.
  • #geo.city# | #geo.stateCode# | #geo.zipCode#
  • Grouping Output In the example data, the same state listed multiple times in relation to the multiple cities that are associated to each state. You can also see the same city listed multiple times in relation to the multiple zip codes associated to each city. Let's group the output by state first. Notice the 2nd instance of cfloop wrapped around the content that will be output under the stateCode grouped content.
    • #geo.stateCode#
      • #geo.city# | #geo.zipCode#
    Generated HTML (extract) from one grouped cfloop tag.
    • AK
      • KONGIGANAK | 99545
      • ADAK | 99546
      • ATKA | 99547
    • AL
      • ALEX CITY | 35010
      • ALEXANDER CITY | 35010
      • ALEX CITY | 35011
      https://riptutorial.com/ 13
    Finally, let's group the output by stateCode, then by city in order to see all the zipCode entries per city. Notice the 2nd cfloop is now grouped by city and a 3rd cfloop exists to output the zipCode data.
    • #geo.stateCode#
      • #geo.city#
        • #geo.zipCode#
    Generated HTML (extract) from two grouped cfloop tags.
    • AK
      • ADAK
        • 99546
        • 99571
      • AKHIOK
        • 99615
      • BARROW
        • 99723
        • 99759
        • 99789
        • 99791
    https://riptutorial.com/ 14 CFScript ColdFusion 6 (MX) though current for (x = 1; x LTE geo.recordcount; x = x + 1) { writeOutput( '
  • ' & geo.city[x] & ' | ' & geo.stateCode[x] & ' | ' & geo.zipCode[x] & '
  • '); }
    ColdFusion 8 though current for (x = 1; x <= geo.recordcount; x++) { writeOutput( '
  • ' & geo.city[x] & ' | ' & geo.stateCode[x] & ' | ' & geo.zipCode[x] & '
  • '); }
    ColdFusion 10 though current With the FOR IN syntax, x is a query row object, not the row index. for (x in geo) { writeOutput( '
  • ' & x.city & ' | ' & x.stateCode & ' | ' & x.zipCode & '
  • '); }
    ColdFusion 11 though current ColdFusion 11 allows most tags to be written as cfscript. cfloop(query: geo, startrow: 1, endrow: 2) { writeOutput( '
  • ' & geo.city & ' | ' & geo.stateCode & ' | ' & geo.zipCode & '
  • '); }
    With group. cfloop(query: geo, group: 'city') { writeOutput( '
  • ' & geo.city & '
      '); cfloop() { // no arguments, just as in the tag syntax. https://riptutorial.com/ 15 writeOutput('
    • ' & geo.zipCode & '
    • '); } writeOutput('
  • '); }
    List Consider this list: Tag syntax Parameters Attribute Required Default Description list true A list object. The variable must be evaluated (wrapped with ##) index true The current element of the list.
  • #x#
  • Generated HTML This will also have a line break between each line of HTML.
  • one
  • two
  • three
  • four
  • CFScript Previous to ColdFusion 8 for (x = 1; x LTE listLen(foo); x = x + 1) { writeOutput("
  • " & listGetAt(foo, x) & "
  • "); https://riptutorial.com/ 16 }
    ColdFusion 8 through current for (x = 1; x <= listLen(foo); x++) { writeOutput("
  • " & listGetAt(foo, x) & "
  • "); }
    ColdFusion 9 through current for (x in foo) { writeOutput("
  • " & x & "
  • "); }
    ColdFusion 11 through current The cfscript function cfloop has no support for list. Generated HTML Notice that the cfscript output is all on one line.
  • one
  • two
  • three
  • four
  • Array The ability to directly use an array object with cfloop was added in ColdFusion 8. Consider this array; Tag syntax ColdFusion 8 through current https://riptutorial.com/ 17 Using the attribute index by itself. Parameters Attribute Required Default Description array true An array object. The variable must be evaluated (wrapped with ##) index true The current element of the array.
  • #x#
  • Generated HTML This will also have a line break between each line of HTML.
  • one
  • two
  • three
  • four
  • ColdFusion 2016 through current The attribute item changes the behavior of cfloop as of Coldfusion 2016. Using the attribute item instead of or in addition to index. Parameters Attribute Required Default Description array true An array object. The variable must be evaluated (wrapped with ##) item true The current element of the array. index false The current index of the array.
  • #x# | #y#
  • https://riptutorial.com/ 18 Generated HTML This will also have a line break between each line of HTML.
  • one | 1
  • two | 2
  • three | 3
  • four | 4
  • CFScript Previous to ColdFusion 8 for (i = 1; x LTE arrayLen(aFoo); i = i + 1) { writeOutput("
  • " & aFoo[i] & "
  • "); }
    ColdFusion 8 through current for (i = 1; i <= arrayLen(aFoo); i = i++) { writeOutput("
  • " & aFoo[i] & "
  • "); }
    ColdFusion 9 through current With the FOR IN syntax, x is the current array element, not the array index. for (x in aFoo) { writeOutput("
  • " & x & "
  • "); }
    ColdFusion 11 through current The cfscript function cfloop has no support for array. Generated HTML Notice that the cfscript output is all on one line. https://riptutorial.com/ 19
  • one
  • two
  • three
  • four
  • File #FileItem#
    Structure Consider this structure: Tag syntax Parameters Notice the use of the attribute item instead of index. Attribute Required Type Default Description collection true structure A struct object. The variable must be evaluated (wrapped with ##). item true string The current structure key, Using Structure Functions
  • #structFind(stFoo, x)#
  • Implicit Structure Syntax https://riptutorial.com/ 20
  • #stFoo[x]#
  • Generated HTML This will also have a line break between each line of HTML.
  • one
  • two
  • three
  • four
  • CFScript With the FOR IN syntax, x is a key of the structure object. Output the structure's keys for (x in stFoo) { writeOutput("
  • " & x & "
  • "); }
    Generated HTML
  • A
  • B
  • C
  • D
  • Output the value of the structure's keys Using Structure Functions for (x in stFoo) { writeOutput("
  • " & structFind(stFoo, x) & "
  • "); }
    Implicit Structure Syntax for (x in stFoo) { writeOutput("
  • " & stFoo[x] & "
  • "); }
    https://riptutorial.com/ 21 ColdFusion 11 through current The cfscript function cfloop has no support for collection. Generated HTML Notice that the cfscript output is all on one line.
  • one
  • two
  • three
  • four
  • Index Loop Use the from and to attributes to specify how many iterations should occur. The (optional) step attribute allows you to determine how big the increments will be. #i#
    Conditional Loop You use the condition attribute to specify the condition to use. myVar = #myVar# (still in loop)
    myVar = #myVar# (loop has finished) Query Loop You can loop over the results of a ColdFusion query. select top 4 movieName from Movies #movieName# https://riptutorial.com/ 22 List Loop You can use the (optional) delimiters attribute to specify which characters are used as separators in the list. #ListItem#
    File Loop You can loop over a file. #line#
    COM Collection/Structure Loops You can loop over a Structure or COM collection. #subject#: #StructFind(myBooks,subject)#
    Read CFLOOP How-To online: https://riptutorial.com/coldfusion/topic/3035/cfloop-how-to https://riptutorial.com/ 23 Chapter 3: cfquery Parameters Parameter Details name Value: string, Default: yes dbtype Value: query/hql, Default: no, Remarks: when left blank, it's a normal query datasource Default: no, Remarks: database params Value: structure, Default: no, Remarks: cfscript syntax only! In cfml they are written inside SLQ stament using Examples Using cfquery within a Function SELECT id, name FROM user WHERE id = Query of Query Function Calls User.cfc https://riptutorial.com/ 24 SELECT id, name FROM user SELECT id, name FROM arguments.qry WHERE id = Read cfquery online: https://riptutorial.com/coldfusion/topic/6452/cfquery https://riptutorial.com/ 25 Chapter 4: ColdFusion Arrays Syntax • ArrayNew(dimension, isSynchronized) Parameters Name Description Dimension Number of dimensions in new array: 1, 2, or 3 isSynchronized When false, creates an unsynchronized array, When true, the function returns a synchronized array. Remarks In a synchronized array, more than two threads cannot access the array simultaneously. Other threads has to wait until the active thread completes its job, resulting in significant performance. In 2016 ColdFusion release, you can use an unsynchronized array and let multiple threads access the same array object simultaneously. Examples Creating Arrays Creating arrays explicitly using ArrayNew() Declare an array with the ArrayNew function. Specify the number of dimensions as an argument. • • • ArrayNew(dimension) creates an array of 1–3 dimensions. ColdFusion arrays expand dynamically as data is added. ArrayNew() returns an array. History Introduced in ColdFusion MX 6 Declaration CFML https://riptutorial.com/ 26 CFScript Note that inside a function you should use var scoping. Earlier versions of CF required var scoping to be the first thing in a function; later versions allow it anywhere in a function. oneDimensionArray = ArrayNew(1); public void function myFunc() { var oneDimensionArray = ArrayNew(1); } After creating the array, add elements by using the element indexes. The Coldfusion Array index starts from 1: CFML CFScript oneDimensionArray[1] = 1; oneDimensionArray[2] = 'one'; oneDimensionArray[3] = '1'; Using ArrayAppend() You can add elements to an array using the function ArrayAppend(array, value). ArrayAppend(oneDimensionArray, 1); ArrayAppend(oneDimensionArray, 'one'); ArrayAppend(oneDimensionArray, '1'); Output the array contents using : Results: https://riptutorial.com/ 27 CFML CFScript twoDimensionArray = ArrayNew(2); twoDimensionArray[1][1] = 1; twoDimensionArray[1][2] = 2; twoDimensionArray[2][1] = 3; twoDimensionArray[2][2] = 4; Outputting the contents of array using Result: Each element contains another Array, which will store the values. Creating 1-D Array Implicitly When creating an array implicitly, brackets ([]) surround the array contents with comma separators. https://riptutorial.com/ 28 This statement is equivalent to the four statements used to create the above oneDimensionArray. The result are the same when using: Create 2-D Array Implicitly Or: Outputting the content using Alternative Explicit Declaration Also you can declare 1 Dimension Array as oneDimensionArray = []; This declaration is same as that of using ArrayNew(1). But if you try declaring 2 Dimension Array as //Invalid CFML construct https://riptutorial.com/ 29 an error will occur while processing this request. Following statement will process the request: but variable twoDimensionArray will not actually an Array within Array (or 2-Dimension Array). It actually contains structure within Array. Result: Array in CFScript oneDimensionArray = ArrayNew(1); oneDimensionArray[1] = 1; oneDimensionArray[2] = 'one'; oneDimensionArray[3] = '1'; Result: Also, we can declare an one Dimension Array as: https://riptutorial.com/ 30 oneDimensionArray = []; Alternatively, CF introduced WriteDump() from CF9 as a function equivalent to the tag which can be used in . WriteDump(oneDimensionArray); Similarly, for 2 Dimension Array: twoDimensionArray = ArrayNew(2); twoDimensionArray[1][1] = 1; twoDimensionArray[1][2] = 2; twoDimensionArray[2][1] = 3; twoDimensionArray[2][2] = 4; Result: General information First some general information about how arrays behave in Coldfusion as compared to other programming languages. • • • Arrays can have numeric indexes only (if you want to have a string index use structs instead) Arrays begin at index [1] Arrays can have one ore more dimensions Read ColdFusion Arrays online: https://riptutorial.com/coldfusion/topic/6896/coldfusion-arrays https://riptutorial.com/ 31 Chapter 5: Creating REST APIs in coldfusion Introduction REST APIs are interesting when data should be accessed from everywhere including different languages (server and client side). That requires separation from data and processing. Examples Creating backend The interface api_request = GetHttpRequestData(); api = createObject("component","myAPI").init(); #api.welcome()# Read Creating REST APIs in coldfusion online: https://riptutorial.com/coldfusion/topic/10698/creating-rest-apis-in-coldfusion https://riptutorial.com/ 32 Chapter 6: Database Queries Examples Working with databases One of ColdFusion's strengths is how easy it is to work with databases. And of course, query inputs can and should be parameterized. Tag Implementation select firstName, lastName from users where lastName = CFScript Implementation // ColdFusion 9+ var queryService = new query(name="myQuery", datasource="myDatasource"); queryService.addParam(name="lName", value="Allaire", cfsqltype="cf_sql_varchar"); var result = queryService.execute(sql="select firstName, lastName from users where lastName = :lName"); var myQuery = result.getResult(); var myResult = result.getPrefix(); // ColdFusion 11+ var queryParams = {lName = {value="Allaire", cfsqltype="cf_sql_varchar"}}; var queryOptions = {datasource="myDatasource", result="myResult"}; var myQuery = queryExecute("select firstName, lastName from users", queryParams, queryOptions); Inserting values is just as easy: queryExecute(" insert into user( firstname, lastname ) values( :firstname, :lastname ) ",{ firstname: { cfsqltype: "cf_sql_varchar", value: "Dwayne" } ,lastname: { cfsqltype: "cf_sql_varchar", value: "Camacho" } },{ result: "local.insertResult" }); return local.insertResult.generated_key; Basic Example Database connections are set up using the CF Administrator tool. See Database Connections for how to connect a datasource. https://riptutorial.com/ 33 To execute queries all you need is the tag. The tag connects to and opens the database for you, all you need to do is supply it with the name of the datasource. SELECT title FROM Movies To display the query results: #title#
    Authentication Many database configurations require authentication (in the form of a username and password) before you can query the database. You can supply these using the username and password attributes. Note: the username and password can also be configured against the datasource in the ColdFusion Administrator. Supplying these details in your query overrides the username and password in the ColdFusion Administrator. select * from Movies Cached Queries A cached query is a query that has its results stored in the server's memory. The results are stored when the query is first run. From then on, whenever that query is requested again, ColdFusion will retrieve the results from memory. You can cache a query using the cachedAfter attribute. If the query was last run after the supplied date, cached data is used. Otherwise the query is re-run. select * from Movies In order for the cache to be used, and multiple calls to the database be avoided the current query must use the same SQL statement, data source, query name, user name, and password as the cached query used. This includes whitespace in the query. As such the following queries create different caches, even though the trimmed characters are the same and the query results are identical: https://riptutorial.com/ 34 select * from Movies where 1 = 1 where 1 = 1 select * from Movies where 1 = 1 where 1 = 1 Limiting the Number of Records Returned You can limit the number of rows to be returned by using the maxrows attribute. select * from Movies Timeouts You can set a timeout limit using the timeout attribute. This can be useful in preventing requests running far longer than they should and impacting on the whole application as a result. The timeout attribute sets the maximum number of seconds that each action of a query is allowed to execute before returning an error. select * from Movies Read Database Queries online: https://riptutorial.com/coldfusion/topic/4582/database-queries https://riptutorial.com/ 35 Chapter 7: How to invoke a private method dynamically Remarks Use of or invoke() should be faster than evaluate() Examples CFML CFSCRIPT (CF10+) invoke("", somePrivateMethodName, {argument1='one'}); Read How to invoke a private method dynamically online: https://riptutorial.com/coldfusion/topic/6110/how-to-invoke-a-private-method-dynamically https://riptutorial.com/ 36 Chapter 8: Scopes in Coldfusion Introduction A scope is "the range in which a variable can be referenced". ColdFusion knows — as well as most other programming and script languages — several scopes. The following text deals with these types and trys to bring clarity about them, their differences and their characteristics. Examples Request Scopes request variables form url cgi Global Scopes Server Application Session Components and functions variables this local arguments Custom tags attributes thisTag caller https://riptutorial.com/ 37 Common scopes Mostly you're probably working with these scopes: • • • • • • Variables scopeis the scope where all variables are assigned to when nothing else is intentionally declared (like the window scope in JavaScript). Form scopeWhen you send a form to your server, all the form fields which can be identified (by setting the name/id property) are accessible in this scope for further server-side processing. URL scopeAll url query params are stored in that scope this scopeInside a component the this refers to the component itself local scopeVariables declared inside a function using the local statement are encapsulated and only accessible inside that specific function (this is made to avoid pollution of other sopes) Arguments scopeArguments passed to a function inside a component declared by the cfargument tag are accessible with that scope Overview • Components and functions ○ ○ ○ ○ variables this local arguments • Custom tags ○ ○ ○ attributes thisTag caller • Global Scopes ○ ○ ○ Server Application Session • Request Scopes ○ ○ ○ ○ ○ request variables form url cgi Read Scopes in Coldfusion online: https://riptutorial.com/coldfusion/topic/7864/scopes-in- coldfusion https://riptutorial.com/ 38 Chapter 9: Variables Parameters Attribute Description name (Required) Name of the parameter/variable. default (Optional) Value to set parameter to if it does not exist. max min (Optional) The maximum valid value; used only for range validation. (Optional) The minimum valid value; used only for range validation. pattern (Optional) A JavaScript regular expression that the parameter must match; used only for regex or regular_expression validation. type (Optional) The valid format for the data. Examples Using cfset You can set a ColdFusion variable using the tag. To output the variable, you need to surround the variable name with hash # symbols and enclose it within tags. Hello #variablename# Using cfparam The tag creates a variable if it does not already exist. You can assign a default value using the default attribute. This can be used if you want to create a variable, but don't want to overwrite it if it has been previously created elsewhere. Here the variable hasn't been set previously, so it will be assigned with the tag. Hello #firstName# Here the variable has already been assigned using the tag, so this value will override the default value in the tag. https://riptutorial.com/ 39 Hello #firstName# Checking if a Variable Exists You can check if a variable has been defined in a scope by using ColdFusion's built in StructKeyExists() function. This can be used inside a tag to prevent error messages in the event you attempt to refer to a variable that does not exist. You can also use this function to determine whether a user has performed a certain action or not. The syntax for the function is StructKeyExists(structure, "key") The following example checks if the variable firstName exists in the variables scope. Hello #variables.firstname#! Hello stranger! Alternatively, you may use the function: isDefined("scopeName.varName") To avoid ambiguity, it is recommended to declare the scope. For example, If you have a variable in the scope test and you test for name in the global scope, you will get a result of true. isDefined("name") isDefined("x.name") isDefined("test.name") Setting a variable scope It is a common practice to set application variables to an object scope. This keeps them easy to identify and distinguish from variables in other scopes. The Variables scope in a CFC is private to the CFC. When you set variables in this scope, they cannot be seen by pages that invoke the CFC. https://riptutorial.com/ 40 Scopes shared with the calling page include: Form, URL, Request, CGI, Cookie, Client, Session, Application, Server, and Flash. Variables in these scopes are also available to all pages that are included by a CFC. CFC: check_session.cfm

    Welcome back!

    Read Variables online: https://riptutorial.com/coldfusion/topic/4904/variables https://riptutorial.com/ 41 Chapter 10: Working with RegExp Replace callbacks Introduction If you want more than a simple string replacement with common regular expressions you certainly run into trouble and hit the wall when discovering the limits of the regex functions Coldfusion has. There is no build-in function like php's preg_replace_callback. Parameters Parameter Details re str The regular expression The string which should be applyed the the regex callback The function where the captured grouped will be passed in if a match was found. There the matches can be processed Remarks Because Coldfusion itself does not offer what we want, we make recourse to the variety of Java, which is — as we all know — on top of Coldfusion. Java offers us java.util.regex.Pattern. So here is what we actually do: 1. 2. 3. Invoke the Compile method from the Pattern Class object and passing the regex pattern to it (which probably deposits the regex pattern for later use). Invoke the Matcher method on what the Compile method returned and passing the string where the pattern should be executed. Test if matching was successfull by invoking the find method on what the Matcher method returned. If matcher.find() returns true, we could say "That's it", but there is one little thing we have to consider: Java's Pattern object stores the groups and gives us access via another function, which is not always the best way for further processing and not that consistent regarding how other programming languages handle this case. Therefore we loop over matcher.group() so that we can pass an array containing the captured groups to the callback function. And now we can say: "That's it!" Examples https://riptutorial.com/ 42 User defined REReplaceCallback function function REReplaceCallback(re,str,callback) { /* Thanks to Ben Nadel "Learning ColdFusion 8: REMatch() For Regular Expression Matching" from 2007-06-13 https://www.bennadel.com/blog/769-learning-coldfusion-8-rematch-for-regular- expression-matching.htm */ pattern = CreateObject("java","java.util.regex.Pattern").Compile(Arguments.re); matcher = pattern.Matcher(Arguments.str); if(matcher.find()) { groups = []; for(var i = 1; i lte matcher.groupCount(); i++) { ArrayAppend(groups,matcher.group(Val(i))); } return Arguments.callback(groups); } else { return Arguments.callback(false); } } Using REReplaceCallback function REReplaceCallback('YOUR REGEX GOES HERE','AND YOUR STRING HERE',function(groups) { //now you can access the 'groups' array containing all the captured groups return result; //return whatever you've processed inside }); Read Working with RegExp Replace callbacks online: https://riptutorial.com/coldfusion/topic/10655/working-with-regexp-replace-callbacks https://riptutorial.com/ 43 Credits S. No 1 2 3 4 5 6 7 8 9 Chapters Contributors Getting started with coldfusion Adam Tuttle, Adrian J. Moreno, Community, Justin Duhaime, mhatch, RamenChef, shaedrich, Steven Benjamin, user3071284, William Giles CFLOOP How-To Adrian J. Moreno, Bonanza, mhatch, RRK cfquery Bubblesphere, shaedrich ColdFusion Arrays 4444, Justin Duhaime, mhatch, Mishra Shreyanshu, shaedrich Creating REST APIs in coldfusion shaedrich Database Queries Adam Tuttle, Leigh, mhatch, nosilleg, shaedrich, user3071284 How to invoke a private method dynamically Henry Scopes in Coldfusion James A Mohler, shaedrich Variables mhatch 10 Working with RegExp Replace callbacks shaedrich https://riptutorial.com/ 44