ASP Code
ASP Code
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
sql="SELECT DISTINCT Country FROM Customers ORDER BY Country"
rs.Open sql,conn
country=request.form("country")
%>
<form method="post">
Choose Country <select name="country">
<% do until rs.EOF
response.write("<option")
if rs.fields("country")=country then
response.write(" selected")
end if
response.write(">")
response.write(rs.fields("Country"))
rs.MoveNext
loop
rs.Close
set rs=Nothing %>
</select>
<input type="submit" value="Show customers">
</form>
<%
if country<>"" then
sql="SELECT Companyname,Contactname,Country FROM Customers WHERE
country='" & country & "'"
set rs=Server.CreateObject("ADODB.Recordset")
rs.Open sql,conn
%>
<table width="100%" cellspacing="0" cellpadding="2" border="1">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Country</th>
</tr>
<%
do until rs.EOF
response.write("<tr>")
response.write("<td>" & rs.fields("companyname") & "</td>")
response.write("<td>" & rs.fields("contactname") & "</td>")
response.write("<td>" & rs.fields("country") & "</td>")
response.write("</tr>")
rs.MoveNext
loop
rs.close
conn.Close
set rs=Nothing
set conn=Nothing%>
</table>
<% end if %>
</body>
</html>
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM Customers WHERE CompanyName
LIKE 'A%'"
rs.Open sql, conn
%>
<table border="1" width="100%">
<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close
%>
</table>
</body>
</html>
18/01/2010
2. End date:
Choose date
Choose date
3. Test select:
Page sourcecode
$(function()
{
$('.date-pick').datePicker()
$('#start-date').bind(
'dpClosed',
function(e, selectedDates)
{
var d = selectedDates[0];
if (d) {
d = new Date(d);
$('#enddate').dpSetStartDate(d.addDays(1).asString());
}
}
);
$('#end-date').bind(
'dpClosed',
function(e, selectedDates)
{
var d = selectedDates[0];
if (d) {
d = new Date(d);
$('#start-date').dpSetEndDate(d.addDays(1).asString());
}
}
);
});
Page CSS
/* located in demo.css and creates a little calendar icon
* instead of a text link for "Choose date"
*/
a.dp-choose-date {
float: left;
width: 16px;
height: 16px;
padding: 0;
margin: 5px 3px 0;
display: block;
text-indent: -2000px;
overflow: hidden;
background: url(calendar.png) no-repeat;
}
a.dp-choose-date.dp-disabled {
background-position: 0 -20px;
cursor: default;
}
/* makes the input field shorter once the date picker code
* has run (to allow space for the calendar icon
*/
input.dp-applied {
width: 140px;
float: left;
Overview
No matter what kind of site you have got, you will need your ASP pages to access
databases. ASP makes it easier to work with databases by providing support for ADO
( Activex Data Objects ). You already know how to build DSN ( Data Source Name ) and
then access database, if you don't then you might want to check out my tutorial on
Accessing Databases via ASP.
In this article I will build on that tutorial to show you how to add records to the database.
We will begin by exploring the insert statement provided by SQL ( Structured Query
Language ). After that we will see the two basic ways we can use to add records to the
database.
I will assume here that you have read the Accessing Databases via ASP tutorial and are
comfortable creating DSNs and simple Access Databases. I will also assume that you
have got access to Microsoft Access Database, PWS / IIS with a notepad to write ASP
pages.
Syntax
insert into table_name (field1, field2, field3)
values ('value1', 'value2', 'value3';
The insert statement as you have seen above is very simple to understand. It takes three
arguments; table, fields and values. table_name is the name of the table in the database
into which you want to add records. fieldn are the names of the columns in that table into
which you want to add records. valuen are the values which will be inserted into specific
fields. Note field names and values can be one or more than one but the table name will
always be one.
Example
insert into books (author, title) values
('Faisal Khan', 'Add Records';
When run the above query results in the insertion into two fields of table books, author
and title values Faisal Khan and Add Records.
Values
Faisal Khan
Add Records
Now after you are familiar with the insert statement and have seen how it works, it is
time to move forward to see the two ways by which we can easily add records to our
database via ASP.
We manipulate databases in ASP through ADO ( Activex Data Objects ). ADO is a set of
pre made data components which makes things a lot easier for us when it comes to
accessing data stores. Wondering why did I say data stores and not databases ? well,
database is only one of the data stores and ADO can help us access more than that e.g.
XML. We'll not go into what ADO can do for us, instead we'll restrain ourselves to the
discussion of adding records to database via ASP.
There are two ways to add records to the database. We'll discuss each of them now.
%>
The above results in the creation of Connection Object which opens the database and
inserts the records into specific fields of the table according to the SQL insert statement.
See, didn't I say before it was going to be easy.
We didn't use any SQL insert statement here but added the records.
So what should you use ? Connection or Recordset Object, for adding records. Well
Connection Object is fast and uses less server resources while Recordset Object is
resource heavy. So if you have to add records to the database then Connection Object is
usually the preferred way. Whichever you choose is up to you.
Dreamweaver / ASP
it
INSERT
UPDATE
DELETE
command
command
command
together
all
Top
On the page in which you wish to perform the INSERT select Command (Stored Procedure) from
the
Data
Bindings
window.
Give your INSERT command a name, select the connection and select Insert from the Type list.
Dreamweaver can help you build the INSERT command. Click the + symbol next to Tables in the
Database Items box to display a list of tables in you database. Click the + symbol next to the table
into which you wish to insert values. Now click on a column (fields) into which you want to insert a
value and then click the COLUMN button, repeat this for each field you into which you want to
insert a value, you should see the results in the SQL box. Alternatively you can type the INSERT
command directly in the SQL box, either way you should end up with an insert command something
like:
INSERT
INTO
tableName(Field1,
Field2,
Field3)
VALUES('Joe',
'Bloggs',
12345)
This will insert the literal values Job into Field1, Bloggs into Field2 and 12345 into Field3. Notice how
text
values
are
surrounded
by
single
quotes,
numeric
values
without.
If you wish to insert variables or the value submitted from a form click the + button above the
variables box and add the variable in a way similar to setting up variables for a recordset, providing
a
variable
name
and
a
run-time
value,
for
example:
Variables
Name
Run-time Value
strSomeText
Request("TextFieldOneName")
strMoreText
Request("TextFieldTwoName")
intSomeNumber
Request("ListMenuName")
Which
would
produce
an
INSERT
command
like
this:
Notice that variables containing text values are surrounded by single quotes, in the same way as
literal
text
values.
Top
On the page in which you wish to perform the UPDATE select Command (Stored Procedure) from
the
Data
Bindings
window.
Give your UPDATE command a name, select the connection and select UPDATE from the Type list.
Similar to the INSERT command, Dreamweaver can help you build the UPDATE command. Click the
+ symbol next to Tables in the Database Items box to display a list of tables in you database.
Click the + symbol next to the table in which you wish to update values. Now click on a column
(fields) in which you wish to update a value and then click the COLUMN button, repeat this for each
field you wish to update, you should see the results in the SQL box. For the update command you
also have to supply a WHERE clause, click on the field in the database items box and click the
WHERE button. Alternatively you can type the UPDATE command directly in the SQL box, either
way
you
should
end
up
with
an
update
command
something
like:
UPDATE
WHERE
tableName
SET
Field1= 'Joe',
Field4
Field2
'Bloggs'
=
Field3
12345
7
This will update Field1 to Joe, Field2 to Bloggs and Field3 to 12345 in every row of the table where
Field 4 contains the value 7. Notice how text values are surrounded by single quotes, numeric
values
without.
If you wish to update fields with the values stored in variable or the value submitted from a form
click the + button above the variables box and add the variable in a way similar to setting up
variables for a recordset, providing a variable name and a run-time value, for example:
Variables
Name
Run-time Value
strSomeText
Request("TextFieldOneName")
strMoreText
Request("TextFieldTwoName")
intSomeNumber
Request("ListMenuName")
intAnotherNumber
Request("RadioButtonName")
Which
would
UPDATE tableName
intSomeNumber
WHERE
produce
SET
Field1=
Field4
an
UPDATE
'strSomeText',
Field2
=
command
=
like
'strMoreText'
this:
Field3
intAnotherNumber
Notice that variables containing text values are surrounded by single quotes, in the same way as
literal
text
values.
Top
On the page in which you wish to perform the UPDATE select Command (Stored Procedure) from
the
Data
Bindings
window.
Give your DELETE command a name, select the connection and select DELETE from the Type list.
Similar to the INSERT and UPDATE commands, Dreamweaver can help you build the DELETE
command. Click the + symbol next to Tables in the Database Items box to display a list of tables
in you database. Click the + symbol next to the table in which you wish to update values. Now click
on a column (fields) in which you wish to update a value and then click the COLUMN button, repeat
this for each field you wish to update, you should see the results in the SQL box. For the delete
command you also have to supply a WHERE clause, click on the field in the database items box that
you want to use and click the WHERE button. Alternatively you can type the DELETE command
directly in the SQL box, either way you should end up with a delete command something like:
DELETE
This
will
FROM
delete
every
tableName
row
in
the
WHERE
table
where
Field4
Field
contains
the
7
value
7.
If you wish to delete fields by supplying the WHERE clause with a value stored in variable or a value
submitted from a form, click the + button above the variables box and add the variable in a way
similar to setting up variables for a recordset, providing a variable name and a run-time value, for
example:
Variables
Name
Run-time Value
intRecordID
Request("RadioButtonName")
Which
DELETE
would
FROM
produce
tableName
an
DELETE
WHERE
command
Field4
like
=
this:
intRecordID
As with the INSERT and UPDATE commands, both literal and variable values that contain text should
be
surrounded
with
single
quotes,
for
example:
DELETE
FROM
tblUsers
WHERE
Username
'Fred'
Top
If you switch to code view, you will see that each of the commands generates a block of code similar
to that shown below, in fact only the Command1.CommandText line will vary according to
whether you set up an insert, update or delete command.
<%
if(Request("TextField1") <> "") then Command1__varOne = Request("TextField1")
if(Request("TextField2") <> "") then Command1__varTwo = Request("TextField2")
if(Request("TextField3") <> "") then Command1__varThree = Request("TextField3")
%>
< %
set Command1 = Server.CreateObject("ADODB.Command")
Command1.ActiveConnection = MM_YourConnection_STRING
Command1.CommandText = "INSERT INTO TableName(Field1, Field2, Field3) VALUES ('" +
Replace(Command1__varOne, "'", "''") + "', '" + Replace(Command1__varTwo, "'", "''")
+ "', " + Replace(Command1__varThree, "'", "''") + ") "
Command1.CommandType = 1
Command1.CommandTimeout = 0
Command1.Prepared = true
Command1.Execute()
%>
This code will execute as soon as the page loads, which can be useful on occasion, but we usually
only want to perfom record modifications as the result of a form being submitted. To do this simply
put the command within a condition, for example:
<% If Request("SubmitButtonName") <> "" Then %>
<%
COMMAND CODE
%>
<% End If %>
You can also set up multiple commands on a single page in order to insert, update or delete records
in different tables in one instance, for example:
<% If Request("SubmitButtonName") <> "" Then %>
<%
COMMAND CODE - INSERT INTO TABLE1
%>
<%
COMMAND CODE - INSERT INTO TABLE2
%>
<% End If %>
You can also use the commands in conjunction with the retrieve inserted record identity code in
order to insert the new identity into a second table, which is useful if you need to maintain a
relationship between two or more tables, for example:
<% If Request("SubmitButtonName") <> "" Then %>
<%
INSERT INTO TABLE1
RETRIEVE NEW RECORD IDENTITY
%>
<%
COMMAND CODE - INSERT INTO TABLE2(FIELD1, etc.) VALUES(NEW RECORD IDENTITY, etc.)
%>
<% End If %>
Updating Multiple Records using SQL Update and the Where/In Clause with Checkboxes
There may be instances where one wants to update a field value for a large, select group of
records. Doing this one record at a time is a killer on productivity. However, using checkboxes
and a drop-down list, one can select a large group of records and then define a DMX
Command to update the records in one fell swoop. This builds upon an article written by
Marcellino Bommezijn concerning the deletion of multiple records and uses the SQL WHERE IN
clause that he used in that tutorial.
Assumptions:
1.
The person using this tutorial is familiar with databases and connection strings/DSNs.
These will not be covered in this tutorial. I assume that one can setup or already has
setup these conventions to follow the tutorial.
2.
This tutorial references Microsoft Access as the database of choice for this tutorial,
however, this example can be done in MySQL or SQL databases. I assume one has the
knowledge to setup the databases as necessary for whatever server application is
being used.
3.
Setup a table named students with the following field names, types:
student_id,
Autonumber Primary Key
student_name,
text
assigned_group,
text
SELECT *
FROM students
On our form, we will use a list menu to choose which group we are assigning. In this example,
we simply add values to the list, though this could also be populated by another recordset
using Dyanmic assignments in DMX. We will also setup a repeating region for all records in
rs_students. The method of submission will be GET.
The list menu is a simple select tag that looks like this:
<select name="group_option">
<option value="Mathematicians">Mathematicians</option>
<option value="Writers">Writers</option>
<option value="Scientists">Scientists</option>
</select>
The checkbox on the form will be named "update_group" and we will assign the student_id
as a unique value from the recordset. This will look like the following in the HTML code:
<input name="update_group" type="checkbox" id="update_group" value="<
%=(rs_students.Fields.Item("student_id").Value)%>">
The following shows the <form> attributes: <form name="assign_groups_form"
method="get" action="proc_student_group_update.asp">
Save this file.
Step 2: Designing the Update Process
To create the update page, we are going to setup a SQL command using the Command option
under the Server Behaviors. Save this file as proc_student_group_update.asp before going
any further.
With the Command dialogue box open, we will define the following.
1.
2.
From the Connection list, either define your connection or select a pre-defined
connection name, in my case cnnUtility.
3.
4.
5.
We are setting the field named assigned_group the value of group_option from the
form. Since we are using a GET method, we assign the run-time value for variable
param_group by using Request.QueryString("group_option"). Since this is a string of
text, we need to put param_group variable inside single quotes for the SQL
statement.
6.
We are updating all records that have been checked in update_group from the form.
Because we used the same name on the form for the checkbox, the values will be
stored as a comma-delimited list. We assign the run-time value for variable
param_students by using Request.QueryString("update_group"). Since we are using
IN as part of the WHERE clause, the SQL Update will make changes to all records
with a matching student_id value in the recordset. As the student_id values are
integers, they do not need to be placed in single quotes.
7.
Finally, a little clean up is needed. Just below the section where DMX writes the
COMMAND code, add the following to ensure the release of the
update_group_assignment command variable:
<%
SET update_group_assignment = nothing
%>
Step 3: Finishing Up
1.
In the Head section place a Refresh tag that redirects to the first form, like so:
<meta http-equiv="refresh" content="5;URL=frm_assign_group_students.asp">
2.
3.
4.
We are finished.
Updating Multiple Records using SQL Update and the Where/In Clause with Checkboxes
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
< !-- Include Files for the pre-header excluding JavaScript and CSS -->
< !--#include file="../../Connections/cnn_Utility.asp" -->
< !-- Macromedia VB Script and ASP not in the body -->
<%
if(Request.QueryString("group_option") <> "") then
update_group_assignment__param_group = Request.QueryString("group_option")
if(Request.QueryString("update_group") <> "") then
update_group_assignment__param_students = Request.QueryString("update_group")
%>
<%
set update_group_assignment = Server.CreateObject("ADODB.Command")
update_group_assignment.ActiveConnection = MM_cnn_Utility_STRING
update_group_assignment.CommandText = "UPDATE students SET assigned_group = '" +
Replace(update_group_assignment__param_group, "'", "''") + "' WHERE student_id IN (" +
Replace(update_group_assignment__param_students, "'", "''") + ") "
update_group_assignment.CommandType = 1
update_group_assignment.CommandTimeout = 0
update_group_assignment.Prepared = true
update_group_assignment.Execute()
%>
< !-- Nexsys Design VB Script and ASP not in the body -->
<%
SET update_group_assignment = nothing
%>
< html>
< head>
< title>Developed by Nexsys Design</title>
< !-- Meta Tags Section in the Head-->
< meta name="author" content="[email protected]">
< meta name="copyright" content="Copyright 1998 - 2003, Nexsys Design, Inc.">
< meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
< meta http-equiv="refresh" content="5;URL=frm_assign_group_students.asp">
<!-- Macromedia JavaScript in the Head -->
< !-- Nexsys Design JavaScript in the Head -->
< !-- CSS Links or Style Definitions in the Head -->
< script language="JavaScript" type="text/JavaScript">
< !-function MM_displayStatusMsg(msgStr) { //v1.0
status=msgStr;
document.MM_returnValue = true;
}
//-->
< /script>
< link href="../../nexsysV2.css" rel="stylesheet" type="text/css">
< /head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"
onLoad="MM_displayStatusMsg('Copyright © 2003 - Nexsys Design, Inc. All Rights
Reserved.');return document.MM_returnValue">
< div align="center">
<p> </p>
<p> </p>
<table width="500" border="0" cellpadding="0" cellspacing="0" bgcolor="#EEEEEE"
class="borderTBLR">
<tr>
Using a Stored Procedure with a SQL Server database or creating your own custom INSERT command with
an Access database it's fairly simple to retrieve the identity of the newly created record, something which is
often useful with a record insert. For more information about retrieving record identities with Access and SQL
Server see my site: http://www.drdev.net/
1. Create your form, including a File Field to browse to the file you wish to upload.
2. Now add the Pure ASP Upload server behaviour as you would normally, selecting the options you require.
Don't specify a redirect URL, you can add that after your insert command code if required.
3. Now create your insert command as you wish, but instead of using Request.Form("formElementName")
to collect the values from the form elements, as you would usually, use
CStr(UploadFormRequest("formElementName ")).
For example, you might normally collect the form elements into variables like this:
strFileName = Request.Form("fileUpload")
strTitle = Request.Form("txtTitle")
strDescription = Request.Form("txtDescription")
With the Pure ASP Upload behaviour, modify the collection of the values from the form as follows:
strFileName = CStr(UploadFormRequest("fileUpload"))
strTitle = CStr(UploadFormRequest("txtTitle"))
strDescription = CStr(UploadFormRequest("txtDescription"))
That's it, you can now use the values in the variables with your own insert command whether it uses a
Stored Procedure or it is simply your preferred method of inserting a record in an Access or SQL Server
database.
Here's an example insert command for an Access database which retrieves the identity of the newly created
record and redirects the user to a new page. Notice I've used the Replace single quotes with two single
quotes in this example to stop the INSERT command fowling up if they were included in the string values
entered in the form: