Home > Articles > Programming

  • Print
  • + Share This

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.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.