Inserting Into a Database with ASP

Inserting Into a Database with ASP
The INSERT command is very commonly used in ASP to add rows into a SQL database. Here is the syntax for inserting into your tables.

Let's say that you have built yourself a little guestbook, where visitors have a form in which they can enter their name and comments. You now want to insert that name and comments into the table "GUESTBOOK", to store them and show them to your other visitors. Your GUESTBOOK table has 3 fields:

guest_name
guest_comments
guest_date

So your ASP script starts out knowing the value of the name and comments. If you don't know how to get values from a form, read the Using ASP with Forms article. So you now have the variables GuestName and GuestComments filled in with what the user gave you.

Be sure to read about Handling Apostrophes in Input Fields to make sure your input fields are ready for use in SQL.

To do the update, you would use:

Set objCmd4 = Server.CreateObject ("ADODB.Command")
SQLText = "insert into guestbook values('" & GuestName & "', '" & GuestComments & "', '" & Now() & "'"
objCmd4.ActiveConnection = strConnect
objCmd4.CommandType = &H0001
objCmd4.CommandText = SQLText
objCmd4.Execute intRecords
Set objCmd4 = Nothing

This creates the connection, creates the insert statement, submits it, and then shuts down the connection. Note that the Now() command automatically inserts the current date/time, so you know when this user submitted their comment on your site.

Introduction to ASP Ebook

Download this ebook to get everything you need to know about learning ASP - from a step by step tutorial to function lists, sample code, common errors and solutions, and much more! 101 pages.




RSS
Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Lisa Shea. All rights reserved.
This content was written by Lisa Shea. If you wish to use this content in any manner, you need written permission. Contact Lisa Shea for details.