Home > Articles > Programming

The Insert Script, Part 1: insert.asp

To understand the general structure of an ASP insert script, it's helpful to imagine what you would have to do if you had to manually enter information into a database table. Suppose, for some strange reason, your users phoned in their guest book entries and you had to manually enter this information into a database. What are the steps you would have to take to perform this task? Assuming that your database already existed, you would do the following:

  1. Open the database.

  2. Save the user's information by writing it down on a piece of paper.

  3. Type the info from the piece of paper as a SQL INSERT query and send it to the database to store this information in the proper table.

  4. Close the table and exit the database.

Those are almost the same steps your script has to take to programmatically insert information into your database table. Let's look at each step in detail.

Step 1: Open the Database

Every script you create to write to or read from your database starts with the same two lines of code. The technical details of this code are beyond the scope of our tutorial, but it suffices to say that the first line creates an object that knows how to talk to the database, and the second line opens a specific database.

To create an object that can talk to the database, you call server.createobject and pass "adodb.connection" as the lone parameter:

<%
set conn=server.createobject("adodb.connection")

This object, which we've labeled conn—short for connection—can talk to a variety of different databases, such as Access, SQL Server, and Oracle, to name a few. You need to tell conn which database to talk to (open) and you do this by calling conn.open with a rather lengthy parameter string that contains several pieces of information, the most important of which is the name of your database (see Listing 2).

Listing 2 General Code for Opening a Database Connection

<%
set conn=server.createobject("adodb.connection")
conn.open("DBQ=" & server.mappath("database_folder/database_name") & _
     ";Driver={Microsoft Access Driver (*.mdb)};")

Our database, created in Tutorial 2, is named visualtutorial.mdb, so our parameter string would read as shown in Listing 3.

Listing 3 insert.asp: Code to Open visualtutorial.mdb

'
' Step 1: Open up the database
'
<%
set conn=server.createobject("adodb.connection")
conn.open("DBQ=" & server.mappath("visualtutorial.mdb") & _
     ";Driver={Microsoft Access Driver (*.mdb)};")

Now create the ASP insert script, using your favorite text editor (we'll use Notepad, as described in Tutorial 4):

  1. Create a new file.

  2. Add the lines shown in Listing 3 to your file.

  3. Save the file as insert.asp.

Don't forget, if you named your database something other than visualtutorial.mdb, enter that name instead. Also note that we haven't yet "closed off" the code with an end-percent (%>). We have more stuff to add.

CAUTION

The parameter string in conn.open assumes that we've uploaded the database to the top level of our web server's directory. This is a HUGE security risk. If a malicious user guesses the name of the database, he or she may be able to download our entire database. You should always put your database in a separate folder—whose name only you know—and have your Internet service provider set it up so that users can't download your database from this folder. However, in this tutorial, to save typing we'll assume that the database is uploaded to the top-level directory of your web server; thus, we won't specify a database folder.

You might be wondering about the ampersands (&) in Listing 3. In Visual Basic, an ampersand merely specifies a concatenation operation. That sounds mysterious and complicated, but it's really quite simple. To see how concatenation works, imagine this simple assignment statement:

x="hello" & " " & "world" & "!"

What the ampersands do is cram everything together (the non-technical way of saying "concatenate"). So the above assignment statement is the same as this one:

x="hello world!"

As you'll see when we write the SQL insert query, concatenation allows us to have a single, general INSERT query and then "cram in" specific user information from our HTML form.

Finally, toward the end of the second line in Listing 3 is an ampersand followed by a space and an underscore (& _). The underscore simply means "The following line is part of the current line." If you don't put in the underscore, Visual Basic will try to execute the following line as a separate command, which will cause an error:

";Driver={Microsoft Access Driver (*.mdb)};"

Basically, we just don't want the command to run off the edge of the page in your text editor (or in the InformIT window while you're reading this), so we've broken the line into two pieces and inserted the & _ to indicate that.

We want to emphasize once again that these two lines of code—well, two and a half—are the same for each script you write. The only piece of information that varies is the name of your database. So type this piece of code just once, and then copy-and-paste it as needed into your other scripts.

Step 2: Save the User's Information

It almost goes without saying that before you can store data into your database you need to have some data. What data do you use? The data that your users typed into the controls in the guest book entry form. The question is, how do you get this data from the form? Well, remember that all controls in your HTML forms have names. Getting the values that your user typed into your form is straightforward: Call request.form with the name of the control as a parameter—controlname—enclosed in double quotes (see Listing 4).

Listing 4 General Code for Reading and Storing an HTML Control's Value

v_controlname=request.form("controlname")

Assign the value returned by request.form to a variable. For the variable name, we adopt the convention of placing v_ before the name of the control. This is an arbitrary convention. You can name the variable whatever you want, but we find our code less confusing and easier to maintain when we follow this simple naming convention. So, for example, suppose you want to get what the user entered for his or her email address into your HTML form. The following line would do that:

v_email=request.form("email")

Similarly, to get all of a user's information from the guest book form, you would use the code shown in Listing 5.

Listing 5 Code to Read All Guest Book Control Values

v_name   = request.form("name")
v_email   = request.form("email")
v_hideEmail = request.form("hideEmail")
v_age    = request.form("age")
v_gender  = request.form("gender")
v_comment  = request.form("comment")

Remember, email is the name of the text box labeled E-mail: in your HTML form (refer to Listing 1 and Figure 4). Similarly, to read all the values that the user entered into your HTML form, follow these steps:

  1. Immediately after the code to open the database, add the lines of code shown in Listing 5 to get the user's information.

  2. Save the file.

Your insert script should now look like Listing 6.

NOTE

We've added descriptive comments in the code to make it easier to read. You can add your own comments as needed.

Listing 6 insert.asp: Code to Get and Store Guest Book Information

'
' Step 1: Open up the database
'
<%
set conn=server.createobject("adodb.connection")
conn.open("DBQ=" & server.mappath("visualtutorial.mdb") & _
     ";Driver={Microsoft Access Driver (*.mdb)};")
'
' Step 2: Read the user's information
'
v_name   = request.form("name")
v_email   = request.form("email")
v_hideEmail = request.form("hideEmail")
v_age    = request.form("age")
v_gender  = request.form("gender")
v_comment  = request.form("comment")

With the user's information safely stored away in variables, we can turn our attention to writing the code to store the values into the database.

Step 3: Send a SQL INSERT Query to the Database

In Tutorial 3, we showed you how to create SQL insert queries that added information to a table (GuestBook, in that example). The basic format of the INSERT statement is as follows, where table is the name of a table in your database, fieldnames is a comma-separated list of fieldnames in that table, and values is a comma-separated list of values:

INSERT INTO table(fieldnames) VALUES (values)

An important detail to remember is that the order of the values must match the order of the fieldnames. Here's an example of a SQL INSERT query for our GuestBook table:

INSERT INTO GuestBook(name, email, hideEmail, age, gender,
           comment) VALUES ('Nick Flor', 'nick@flor.com',
           Yes, 30, 'M', 'I love guitars')

If you were inserting the data manually, you would type this query into the SQL query window and then click the Run button—the one with the big red exclamation point, as you probably remember very well from Tutorial 3! To have your script send the query programmatically, you use conn.execute, passing the query as a string (that is, inside double quotes). Listing 7 shows the general format for programmatically sending a SQL INSERT query to the database.

Listing 7 General Code for Sending a SQL Command to the Database

conn.execute("INSERT INTO table(fieldnames) VALUES (values)")

So, substituting our sample SQL INSERT yields the statement shown in Listing 8.

Listing 8 Code to Insert a Specific Record into the GuestBook Table

conn.execute("INSERT INTO GuestBook(name, email, hideEmail, age,
                  gender, comment)
       VALUES ('Nick Flor', 'nick@flor.com', Yes, 30, 'M',
           'I love guitars')")

Notice that the query is contained within a pair of double quotes. As queries can get quite long, cramming the query into a couple of lines makes for a program that is difficult to read. Thus, many script writers space out the query by breaking it into several smaller strings, placing these strings on different lines, and attaching the strings using the ampersand and underscore characters. One way to space out the query is shown in Listing 9.

Listing 9 Spaced-Out Code to Insert a Specific Record into the GuestBook Table

conn.execute("INSERT INTO GuestBook "       & _
"(name, email, hideEmail, age, gender, comment) " & _
"VALUES ( "                    & _
"'" & "Nick Flor"   & "',"          & _
"'" & "nick@flor.com" & "',"          & _
" " & "Yes"      & " ,"          & _
" " & "30"       & " ,"          & _
"'" & "M"       & "',"          & _
"'" & "I love guitars" & "')"          )

Absent the extra double quotes, ampersands, and underscores, which cram all the strings together, this query reduces to the previous SQL INSERT query. Also note that there are spaces instead of single quotes before and after the specific values 30 and Yes, as only string values are contained within single quotes.

The problem with putting this query into our insert script is that it inserts the same values into the database each time it's executed. This is clearly not what we want. We want a query that will insert whatever the user typed into our HTML form. Recall from Step 2 above that we've stored what the user typed into variables. Thus, to make our query work with the values the user entered, we simply substitute the specific values above with the corresponding variables; that is, we substitute the variable v_email for the specific value "nick@flor.com" and so on. Listing 10 shows the updated query.

Listing 10 Code to Insert a User's Record into the GuestBook Table

conn.execute("INSERT INTO GuestBook "       & _
"(name, email, hideEmail, age, gender, comment) " & _
"VALUES ( "                    & _
"'" & v_name      & "',"          & _
"'" & v_email     & "',"          & _
" " & v_hideEmail   & " ,"          & _
" " & v_age      & " ,"          & _
"'" & v_gender     & "',"          & _
"'" & v_comment    & "')"          )

Ready to do it? In your text editor, add the variables:

  1. Immediately after the code that stores the user's information, add the text shown in Listing 10.

  2. Save your file.

Your insert script should now look like Listing 11.

Listing 11 insert.asp: Code to Store User Information into the GuestBook Table

'
' Step 1: Open up the database
'
set conn=server.createobject("adodb.connection")
conn.open("DBQ=" & server.mappath("visualtutorial.mdb") & _
     ";Driver={Microsoft Access Driver (*.mdb)};")
'
' Step 2: Read the user's information
'
v_name   = request.form("name")
v_email   = request.form("email")
v_hideEmail = request.form("hideEmail")
v_age    = request.form("age")
v_gender  = request.form("gender")
v_comment  = request.form("comment")
'
' Step 3: Send a SQL INSERT query
'
conn.execute("INSERT INTO GuestBook "       & _
"(name, email, hideEmail, age, gender, comment) " & _
"VALUES ( "                    & _
"'" & v_name      & "',"          & _
"'" & v_email     & "',"          & _
" " & v_hideEmail   & " ,"          & _
" " & v_age      & " ,"          & _
"'" & v_gender     & "',"          & _
"'" & v_comment    & "')"          )

And that's all there is to getting data out of an HTML form and putting that data into a database.

Before closing the database, let's review step 3 one last time, since it's the most complicated and critical step to get right. First, you need to come up with a SQL INSERT query that you know works. Until you're comfortable creating these queries in your head, you should always follow the procedure in Tutorial 3, where you test your SQL INSERT query manually using the SQL query window in Microsoft Access. With a working SQL INSERT query in hand, you use that query programmatically in your insert script by rewriting it according to the template shown in Listing 12.

Listing 12 General Code to Insert a User's Record into a Table

conn.execute("INSERT INTO table " & _
"(fieldnames) "          & _
"VALUES ( "            & _
"?" & v_controlname1 & "?,"    & _
"?" & v_controlname2 & "?,"    & _
...
"?" & v_controlnameN & "?)")

Make the following replacements:

  1. Replace table with your own table's name.

  2. Replace fieldnames with the field names in that table.

  3. Replace v_controlname1...v_controlnameN with the names of your own variables.

  4. Replace the question marks (?) with a single quote (') or a space. Text and memo fields get the single quote; all others get a space.

Step 4: Close the Table and Exit the Database

The script analog to manually closing a table and exiting the database program is closing the database connection and freeing up any memory occupied by your object. You do this with the two lines shown in Listing 13.

Listing 13 General Code to Close a Database Connection

conn.close
set conn=nothing

All your insert scripts will end this way. Don't forget to add these two lines once you've finished inserting into the database. Failure to do so may result in your web server's memory slowly being "eaten up" and your site mysteriously crashing.

In your text editor, finish up the insert script:

  1. Add the code lines shown in Listing 13.

  2. Save your file.

Listing 14 shows our completed insert script.

Listing 14 insert.asp: The Complete Insert Script

<%
'
' Step 1: Open the database
'
set conn=server.createobject("adodb.connection")
conn.open("DBQ=" & server.mappath("visualtutorial.mdb") & _
     ";Driver={Microsoft Access Driver (*.mdb)};")
'
' Step 2: Read the user's information
'
v_name   = request.form("name")
v_email   = request.form("email")
v_age    = request.form("age")
v_gender  = request.form("gender")
v_comment  = request.form("comment")
v_hideEmail = request.form("hideEmail")
'
' Step 3: Send a SQL INSERT query
'
conn.execute("insert into GuestBook "     &_
"(name,email,hideEmail, age,gender,comment) " & _
"values ("                  & _
"'" & v_name   & "'," & _
"'" & v_email   & "'," & _
" " & v_hideEmail & " ," & _
" " & v_age    & " ," & _
"'" & v_gender  & "'," & _
"'" & v_comment  & "')")
'
' Step 4: Close and exit the database
'
conn.close
set conn=nothing
%>

The insert script above will work, but it's not very robust. One big problem is that there's no error handling. For example, if the user forgets to fill in some information, blanks will be inserted into the database table; or, even worse, the script will crash! There is also this common scripting bug known as the "single-quote bug"—if your user types a single quote in a text box, your insert script will crash unless you handle this bug. The next section looks at how to handle these errors.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020