You usually use the following two application pages to update data in a database:
You can create an update form with cfform tags or HTML form tags. The update form calls an update action page, which can contain either a cfupdate tag or a cfquery tag with a SQL UPDATE statement. The update action page should also contain a confirmation message for the end user.
The following are the key differences between an update form and an insert form:
A primary key is a fields in a database table that uniquely identifies each record. For example, in a table of employee names and addresses, only the Emp_ID is unique to each record.
The easiest way to designate the primary key in an update form is to include a hidden input field with the value of the primary key for the record you want to update. The hidden field indicates to ColdFusion which record to update.
The following table describes the code and its function:
Code |
Description |
---|---|
<cfquery name="GetRecordtoUpdate" datasource="cfdocexamples"> SELECT * FROM Employee WHERE Emp_ID = #URL.Emp_ID# </cfquery> |
Queries the cfdocexamples data source and returns records in which the employee ID matches what was entered in the URL that called this page. |
<cfoutput query="GetRecordtoUpdate"> ... </cfoutput> |
Makes available as variables the results of the GetRecordtoUpdate query in the form created in subsequent lines. |
<form action="update_action.cfm" method="Post"> ... </form> |
Creates a form whose variables are processed on the update_action.cfm action page. |
<input type="Hidden" name="Emp_ID" value="#Emp_ID#"><br> |
Uses a hidden input field to pass the Emp_ID (primary key) value to the action page. |
First Name: <input type="text" name="FirstName" value="#FirstName#"><br> Last Name: <input type="text" name="LastName" value="#LastName#"><br> Department Number: <input type="text" name="Dept_ID" value="#Dept_ID#"><br> Start Date: <input type="text" name="StartDate" value="#StartDate#"><br> Salary: <input type="text" name="Salary" value="#Salary#"><br> |
Populates the fields of the update form. This example does not use ColdFusion formatting functions. As a result, start dates look like 1985-03-12 00:00:00 and salaries do not have dollar signs or commas. The user can replace the information in any field using any valid input format for the data. |
Contractor: <cfif #Contract# IS "Yes"> <input type="checkbox" name="Contract" checked>Yes<br> <cfelse> <input type="checkbox" name="Contract"> Yes <br> </cfif> <br> <input type="Submit" value="Update Information"> </form> </cfoutput> |
The Contract field requires special treatment because a check box appears and sets its value. The cfif structure puts a check mark in the check box if the Contract field value is Yes, and leaves the box empty otherwise. |
You can create an action page to update data with either the cfupdate tag or cfquery with the UPDATE statement.