Insert Record and Retrieve Unique ID

There are some instances where you will need to insert a record to a database and, at the same time, need to retrieve the unique ID that was just created for that record.  For example, a visitor may register on your website to become a customer.  When they complete their registration, you may want to give them a unique Member ID #.

To do this, create a database called MyMembers and create a table called tblMemberInfo with these fields:
ID – autonumber
Email – text field
Name – text field
DateEntered – date/time field


Next, create a form page called /Register.asp and copy the below code into your page:

<form name="YourFormName" method="Post" action="confirmation.asp">
<tr><td>Email: </td>
<td><input type="text" name="Email" size="50"></td></tr>
<tr><td>Name: </td>
<td><input type="text" name="Name" size="50"></td></tr>

<input type="submit" name="Submit" value="Submit Form">
Then, create a page called /Confirmation.asp and copy the below code into your page:

<!--#include virtual="/includes/connection.asp" -->

Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "tblCustomerInfo", objConn, , adLockOptimistic, adCmdTable

objRS("Email") = Request.Form("Email")
objRS("Name") = Request.Form("Name")
objRS("DateEntered") = Date()

DIM bookmark
bookmark = objRS.absolutePosition
objRS.absolutePosition = bookmark

DIM strMemberID
strMemberID = objRS("ID")

<p>Thank you for registering with us.  Here is your Member ID: <% =strMemberID %></p>

Set objRS = Nothing
Set objConn = Nothing

There you have it.  Now you can insert a new record, retrieve its unique ID, and display it on your page all in one fell swoop!

< Back to ASP Scripts