In my opinion, one of the most annoying things about some websites is logging in. Today, Mitchell will demonstrate how to create a nifty little feature that will allow your site to "remember" its visitors.
We've just created a pretty simple HTML form. A couple of things to note though: The form is posting the results to adduser.asp, which means that we are posting to the same script. We are also using a hidden input tag to set the value of a request variable named "what" to "addnew".
It's a common practice these days to post the results of a form back to the page that called it and distinguish what the page should display using hidden form variables. In our example above, the hidden "what" variable will be used to tell our script that we want to add a new user. To workout whether or not we are displaying the form to collect the users details, or actually adding the user to our database, we will use a select case statement. Add the following code to the top of your adduser.asp file.
3. dim strWhat
4. strWhat = Request.Form("what")
6. select case strWhat
7. case "addnew"
9. case else
11. end select
13. sub ShowUserForm()
34. end sub
36. sub ProcessUser()
38. dim objConn
39. dim strUserName
40. dim strPassword
42. set objConn = Server.CreateObject("ADODB.Connection")
43. strUserName = Request.Form("uname")
44. strPassword = Request.Form("pass")
46. objConn.Open "Provider=SQLOLEDB; Data Source=localhost; Initial Catalog=smartlogin; UId=sa; Pwd="
50. Response.Write "New user " & strUserName & " added OK."
52. end sub
The code above splits our adduser.asp page into two sub routines. On line 4 we're setting the variable that will tell our script what to do. If a form is being posted, the Request.Form(“what”) key will contain the value “adduser”. If not, it will contain nothing, meaning that there is no form posted and that we should call our ShowUserForm sub that will display the form.
On the other hand, if the Request.Form(“what”) variable contains the value “adduser”, we will call the ProcessUser sub routine which uses an ADO connection object to connect to our database and execute an INSERT query. This INSERT query takes the username and password values from the form and inserts them into a new row in our logins table, thus creating a new user. Lastly, our ASP script simply prints out “New user John added OK.” (Assuming the name of the user we added was John).
Note that for simplicity, all error checking is omitted from the sample we're creating. Now that we can add users to our logins table, we will want to let the users login and “remember them”.