PDA

View Full Version : Adding Records with a Checkbox Field


admin
06-06-2003, 02:29 PM
Many people who are new to ASP have trouble with the checkbox (as well as the radio) field. This article will demonstrate how to insert the contents of a form into a database. The following form uses a checkbox as one of the form fields.

Suppose you have a database table with the following fields:
-ID : autonumber : primary key
-FName : text : first name
-LName : text : last name
-City : text : city
-Service : text : service offered (ie advertising, site design, ecommerce)
-Active : yes/no (the checkbox)


<html>
<body>

<form method="Post" Action="insert.asp">
FirstName: <input type="text" name="fname" size="20">
LastName: <input type="text" name="lname" size="20">
City: <input type="text" name="city" size="20">
Service: <input type="text" name="service" size="20">

'set the value of the checkbox to 1 (True)
Active: <input type="checkbox" name="active" value=1>
<input type="submit" name="add" value="Add Record">
</form>

</body>
</html>



That's it for the form. Save this page as form.htm.

Now create the page that inserts the form contents into a database...

<%@ Language=VBScript%>
<% Response.Buffer = True %>

<html>
<body>

<%
'grab the form contents
fname=Replace(Request.Form("fname"), "'", "''")
'use the Replace() function to replace any apostrophe with double apostrophes. otherwise you'll get a nasty error message if the user types in a value that contains an apostrophe, such as O'Brien

name=Replace(Request.Form("lname"), "'", "''")
city=Replace(Request.Form("city"), "'", "''")
service=Replace(Request.Form("service"), "'", "''") active=request.form("active")

'check to see if the checkbox was checked. if it wasn't then you'll need to set the value = 0, otherwise you'll get an error message.

'The value will be 1 if it is checked.
if active = "" then active = 0

Set MyConn=Server.CreateObject("ADODB.Connection")

'uncomment the second connStr if you want to use OLE DB
'also be sure to change the path and database name to your's
connStr="Driver={Microsoft Access Driver (*.mdb)}; DBQ=c:\Databases\demo.mdb"
'connStr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Databases\demo.mdb"

SQL = "Insert Into Customers(FName, LName, City, Service, Active) Values('"&fname&"','"&lname&"','"&city&"','"&service&"','"&active&"')"

MyConn.Open connStr
MyConn.Execute(SQL)

MyConn.Close
Set MyConn = Nothing
%>

Record Added.

</body>
</html>



Save this page as insert.asp. And that's it.