You usually use two application pages to insert data into a database:
- An insert form
- An insert action page
You can create an insert form with standard HTML form tags or with cfform tags (see Creating custom forms with the cfform tag). When the user submits the form, form variables are passed to a ColdFusion action page that performs an insert operation (and whatever else is called for) on the specified data source. The insert action page can contain either a cfinsert tag or a cfquery tag with a SQL INSERT statement. The insert action page should also contain a confirmation message for the end user.
Creating an HTML insert form
The following procedure creates a form using standard HTML tags. The form looks like the following in your web browser:
- Create a ColdFusion page with the following content:
<html>
<head>
<title>Insert Data Form</title>
</head>
<body>
<h2>Insert Data Form</h2>
<table>
<!--- begin html form;
put action page in the "action" attribute of the form tag. --->
<form action="insert_action.cfm" method="post">
<tr>
<td>Employee ID:</td>
<td><input type="text" name="Emp_ID" size="4" maxlength="4"></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="Text" name="FirstName" size="35" maxlength="50"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="Text" name="LastName" size="35" maxlength="50"></td>
</tr>
<tr>
<td>Department Number:</td>
<td><input type="Text" name="Dept_ID" size="4" maxlength="4"></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="Text" name="StartDate" size="16" maxlength="16"></td>
</tr>
<tr>
<td>Salary:</td>
<td><input type="Text" name="Salary" size="10" maxlength="10"></td>
</tr>
<tr>
<td>Contractor:</td>
<td><input type="checkbox" name="Contract" value="Yes" checked>Yes</td>
</tr>
<tr>
<td> </td>
<td><input type="Submit" value="Submit"> <input type="Reset"
value="Clear Form"></td>
</tr>
</form>
<!--- end html form --->
</table>
</body>
</html>
- Save the file as insert_form.cfm in the myapps directory under your web_root and view it in your web browser.
Data entry form notes and considerations
If you use the cfinsert tag in the action page to insert the data into the database, you should follow these rules for creating the form page:
- You only need to create HTML form fields for the database columns into which you will insert data.
- By default, cfinsert inserts all of the form's fields into the database columns with the same names. For example, it puts the Form.Emp_ID value in the database Emp_ID column. The tag ignores form fields that lack corresponding database column names.
Note: You can also use the formfields attribute of the cfinsert tag to specify which fields to insert; for example, formfields="prod_ID,Emp_ID,status".
Creating an action page to insert data
You can use the cfinsert tag or the cfquery tag to create an action page that inserts data into a database.