Inserting Data

The action page that you build to insert data needs to include:

Building a query to insert data

The CFQUERY tag supports a number of SQL statements that you use to insert, update, and delete records in a table.

For example, you'll use the INSERT statement to insert data into a database.

SQL INSERT syntax

<CFQUERY NAME="QueryName" DataSource="DataSourceName">
    INSERT INTO Table
    (ColumnName, ColumnName,..)
    VALUES
    ('ValueToInsert','ValueToInsert',..)
</CFQUERY>

Inserting data usage example

This code inserts an employee's last name and first name into the Employees table:

<CFQUERY NAME="AddEmployees" DATASOURCE="HRApp">
    INSERT INTO Employees
    (FirstName, LastName)
    VALUES
    ('#Form.FirstName#','#Form.LastName#')
</CFQUERY>
Note Note:The purpose of this guide is to get you up and running with ColdFusion Express. Allaire suggests that you purchase a book on SQL to learn how to use it efficiently.
Note To build an insert action page:
  1. Open InsertAction.cfm in HomeSite.
  2. Title the page Chapter 10- ADD EMPLOYEE ACTION PAGE.
  3. Set a local variable, ContractStatus, to a value of YES if the FORM.Contract variable exists on the action page and set it to NO if the variable does not exist:
  4. <CFIF IsDefined("Form.Contract") IS "Yes">
        <CFSET ContractStatus="Yes">
    <CFELSE>
        <CFSET ContractStatus="No">
    </CFIF>
    

    This ensures that a contract value always passes to the database.

  5. Begin a query named InsertEmployee:
  6. <CFQUERY NAME="InsertEmployee" DATASOURCE="HRExpress">
    
  7. Add a SQL INSERT statement to the query to insert the variables passed from the INSERTFORM.CFM page and the local variable ContractStatus INTO the EMPLOYEES table:
  8. INSERT 
    INTO Employees
    (FirstName, LastName, Department_ID, StartDate, Salary, Contract)
    VALUES
    ('#Form.FirstName#','#Form.LastName#', 
    #Form.Department_ID#,#Form.StartDate#, #Form.Salary#, 
    '#ContractStatus#')
    
  9. End the query:
  10. </CFQUERY>
    
  11. After the query, redirect the user to EmpList.cfm.
  12. <CFLOCATION URL="EmpList.cfm">
    
  13. Save the page.
  14. Test InsertAction.cfm by adding employees to the database.

Click here to see how the form and action page should work.

Click here to see InsertAction.cfm's code.

Move on in this chapter to learn about updating data.

Note Note:Almost all links will work at this time.