Databases and Cookies - Using Cookies with ADO and a Database
(Page 7 of 13 )
Now that we have reviewed using cookies with ASP we can see how to enhance those techniques with ASP–ADO. The syntax is direct, but students can be confused by how to handle the information across multiple pages. Setting a cookie and making a new record in a database is generally done in three pages.
The first page gathers information in a form, this page requires neither ASP nor ADO, just simple HTML forms. That information is passed to an ASP/ADO response page, which performs two jobs. It sets the cookie on the user's PC, and writes the information to the database. Since the user sees neither of those processes, I usually include some text that repeats the data back to the user, and notes that a cookie has been set and they have been entered in the database, along with a hyperlink button to request the third page.
As a robust test we then write a third page to test our process, usually by reading the cookie and using it to look up the visitor's information. I usually add a button here that allows the user to catch a mistake. That button takes the visitor to an editing screen to correct the errors.
Reading Cookies for Use in Database Look-Up Once a cookie is set we can use it in subsequent visits to link the visitor to our database. For example, we can use the ID to find out the sailor's state and then feature on the web page regattas proximal to that sailor.
Sample Syntax to Use a Cookie for Database Look-up Cookies are used to obtain specific information from a database by including them in a SQL statement WHERE clause. This is usually performed over two blocks of code, the first is to get the cookie into a variable, and the second is to use the contents of that variable in the WHERE clause of a SQL statement that gets data from the specific record of the visitor:
<%
Dim varCookieHolder
varCookieHolder=Request.Cookies("MyCookie")
Dim oRecordSet
Set oRecordSet = Server.CreateObject("ADODB.Recordset")
sqltext = "SELECT * FROM MyTable WHERE RecordID=" & varCookieHolder
oRecordSet.Open sqltext, "DSN=MyDataSource"
Response.Write "Data from Table is " & oRecordSet
("MyField")
%>
The most common problem here is failure of the SQL statement when the cookie's data is different from expectations. For example, since MyCookie data could hold an ID for a record that has been deleted, you should check that the resulting recordset has a record prior to trying to use it. An additional problem could be when there is no cookie in the request. This condition must be tested and resolved prior to running a SQL statement with an empty WHERE clause.
This is from Beginning ASP Databases by Kauffman, Spencer, and Willis (Apress, ISBN 1590592492). Check it out at your favorite bookstore today.
Buy this book now. |
Next: Try It Out – Setting a Cookie Using ASP–ADO >>
More ASP.NET Articles
More By Apress Publishing