Adding Data To Access Database

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Adding Data To Access Database as PDF for free.

More details

  • Words: 4,894
  • Pages: 24
ASP and Java Script reference

Page 1 of 24

Adding Data to Access Database To add data to a database table, you need an existing database plus the table to add the data to. Let us assume that you have Access Database file name FeedBack.mdb in the same folder as this file with the following table: tblFeeds Field Name Data Type Field Size user_id Autonumber 8 Name Text 45 Comments Text 200<> To add a data to the table tblFeeds, first we will have to create a form to enter the data and then open the database and make the connection. Here is the form to enter the data before adding to the database: Form Example Adding to database example <script type="text/javascript">
Name:
Comments:
http://www.aspnetcenter.com Page 1 of 24

ASP and Java Script reference

Page 2 of 24

Now, you insert the new record to the database using the information provided through EnterData.asp. Here is the code to do this: save.asp <% Dim Conn Dim Rs Dim sql 'Create an ADO connection and recordset object Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") 'Set an active connection and select fields from the database Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") sql= "SELECT name, comments FROM tblFeeds;" 'Set the lock and cursor type Rs.CursorType = 2 Rs.LockType = 3 Rs.Open sql, Conn

'Open the recordset with sql query

Rs.AddNew 'Prepare the database to add a new record and add Rs.Fields("name") = Request.Form("name") Rs.Fields("comments") = Request.Form("comments") Rs.Update 'Save the update Rs.Close Set Rs = Nothing Set Conn = Nothing %> The third field (user_no) of our table is auto generated and sequentially will accommulate it self on each addition of new record. You redirect the user to another page when the record is added to the database using <%response.redirect("view.asp")%> After the data is added to the database, the next thing you may want do is view to see what is added. The code is very similar. This code bellow displays the fields. view.asp <% Dim Conn Dim Rs Dim sql Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") http://www.aspnetcenter.com

Page 2 of 24

ASP and Java Script reference Page 3 of 24 sql= "SELECT name, comments FROM tblFeeds;" Rs.Open sql, Conn Do While not Rs.EOF Response.Write ("============================================="&"
") Response.Write ("Name: " & "" & Rs("name") & "") Response.Write ("
") Response.Write ("Comment: " & "" & Rs("comments") & "") Response.Write ("
") Rs.MoveNext Loop Rs.Close Set Rs = Nothing Set Conn = Nothing %>

Update a record There are more than one way to do things. For this example, we are going to list items from the database so that you can select a record using radio button. Code to list records from tblFeeds Select name to update. <% Dim Conn, Rs, sql Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") sql= "SELECT * FROM tblFeeds;" Rs.Open sql, Conn Response.Write "
" Response.Write "" Response.Write ""&""&"" Response.Write ""&""&""&"" if NOT Rs.EOF then Do While not Rs.EOF Response.Write ("") Response.Write ("") Response.Write ("") Response.Write ("") Response.Write ("") Rs.MoveNext http://www.aspnetcenter.com

Page 3 of 24

ASP and Java Script reference Page 4 of 24 Loop else Response.Write("No records found") end if Response.Write(""&""&"") Response.Write "
"&"Select a comment to update and click select"&"
"&"Name"&""&"Comment"&"
"&""&""&Rs("name")&""&Rs("comments")&"
"&""&"
" Rs.Close Set Rs = Nothing Set Conn = Nothing %>
User_ID is a unique field which identifies the selected record. When the user selects record and clicks on Select, the information is processed in the toUpdatT.asp file. toUpdateT.asp file allows the user edit the record
<% Dim ID, name, comments ID= Request.Form("ID") name = Request.Form("name") comments=Request.Form("comments") if name="" then Response.Write "You did not select a name to update!" Else Dim Conn, Rs, sql Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") sql= "Select * FROM tblFeeds WHERE user_id="&ID Rs.Open sql, Conn if NOT Rs.EOF then %> http://www.aspnetcenter.com Page 4 of 24

ASP and Java Script reference Page 5 of 24
Update and save
Name: ">
Comment: ">
<% else Response.Write("Record does not exist") end if Conn.Close Set Conn = Nothing End If %> After the new data is entered, the next thing is to save the data and the following is the file to do that. updateComment.asp saves the new information <% Dim name,comments, user_id ID = Request.Form("ID") name = Request.Form("name") comments=Request.Form("comments") if name="" OR comments="" then Response.Write "A field was left empty, please try again!" Else Dim Conn ,Rs, sql Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") sql= "Update tblFeeds Set name='"& name & "', comments='" & comments &"' WHERE user_id=" & ID Rs.Open sql, Conn Conn.Close Set Rs=Nothing Set Conn = Nothing Response.Write "Successfully Updated" End If %>

Delete a record http://www.aspnetcenter.com

Page 5 of 24

ASP and Java Script reference Page 6 of 24 We are going to use two files in order to delete a record. First file (toDelete.asp) is to view all the records and the second file (deleteComment.asp) is to delete selected record. Code to list records from tblFeeds Select name to delete. <% Dim Conn, Rs, sql Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") sql= "SELECT * FROM tblFeeds;" Rs.Open sql, Conn Response.Write "
" Response.Write "" Response.Write ""&""&"" Response.Write ""&""&""&"" Do While not Rs.EOF Response.Write ("") Response.Write ("") Response.Write ("") Response.Write ("") Response.Write ("") Rs.MoveNext Loop Response.Write(""&""&"") Response.Write "
"&"Select a comment to delete and click delete"&"
"&"Name"&""&"Comment"&"
"&""&""&Rs("name")&""&Rs("comments")&"
"&""&"
" Response.Write "
" Rs.Close Set Rs = Nothing Set Conn = Nothing %> The purpose of this file to view records and select one. Selected record is deleted through deleteComment.asp file. deleteComment.asp file <% Dim ID ID = Request.Form("ID") if ID="" then Response.Write "You did not select a name to delete!" Else Dim Conn http://www.aspnetcenter.com

Page 6 of 24

ASP and Java Script reference Dim Rs Dim sql Set Conn = Server.CreateObject("ADODB.Connection") Set Rs = Server.CreateObject("ADODB.Recordset") Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("FeedBack.mdb") sql= "Delete * FROM tblFeeds WHERE user_ID='" & ID Rs.Open sql, Conn Conn.Close Set Conn = Nothing Response.Write "Successfully Deleted" End If %>

Page 7 of 24

Processing forms using ASP You can process HTML forms using these two powerful ASP objects, Response and Request. Response outputs the value to a page and Request retrieves values from an object. Take a look at the following example: form name=”userForm” method=”post” Result action=”userForm.asp”> Enter a user name: Enter a user name: Enter a password: Enter a password: We just created HTML form and tell the browser to process the form using the file "userForm.asp". The following is userForm.asp file that writes the values from the form. Process form Info You have typed the user name <%=Request.Form("userName")%> and the password <%=Request.Form("password")%>. Form Processing Example 2 You can store value retrieved from form into variables in order to use these value whatever way you want. Take a look these at this example which is little bit more complex then previous one. http://www.aspnetcenter.com

Page 7 of 24

ASP and Java Script reference

Page 8 of 24

Form Example 2

This example process basic form elements

Your name:
Status: Customer Visitor
Do you own any of these trucks:
Land Cruiser
Sequoia
4Runner
Highlander
Tundra Access Cab
Car of Choice:<select size="1" name="product">
Enter some general comments about what you think about Toyota cars:


Result of the above code Code for formProcess.asp This example process basic form Result of your information elements Your name: <% Status: Customer Visitor dim name, status, truck, car, comments Do you own any of these trucks: name=Request.Form("Name") Land Cruiser status=Request.Form("status") Sequoia car=Request.Form("car") 4Runner comments=Request.Form("comments") Highlander truck=Request.Form("truck") Tundra Access Cab %> Car of Choice: http://www.aspnetcenter.com

Page 8 of 24

ASP and Java Script reference

Page 9 of 24 Your name: <%=name%>
Status: <%=status%>
Your favourite car is: <%=car%>
You currently own these trucks: Any comments about Toyota cars: <%=truck%>
Your comments about Toyota products:<%=comments%> Type some information into the form elements and hit submit to see the code in action.

ASP Cookies A cookie is object used to identify the user by his/her computer. Each time the same computer access the page, the cookie will also be retrieved if the expiry date has future value. Creating cookies in asp is very simple. Use Response.Cookie to create a cookie or Request.Cookie to read a cookie. The following example creates a cookie named userName and assigns value: <% Response.Cookies("userName")="user123" %> The example bellow will retrieve the cookie we create above: <% user=Request.Cookies("userName") response.write("Welcome " & user) %> The result of the above example will look like this: welcome user123 The cookie will be deleted after your browser is closed unless you set the expiry date to a future date. The following example will keep the cookie in place for 30 days after setup date: <%

Response.Cookies("userName")="user123" Response.Expires("userName").Expires = Date + 30

%>

You can also set a cookie with multiple values like the following: <% Response.Cookies("user")("userName") = "Bell" Response.Cookies("user")("firstName") = "Bellion" Response.Cookies("user")("lastName") = "Briabion" %>

The above Cookie has Keys. When you want retrieve a cookie with multiple values, you will have to loop through the values using for loop statement http://www.aspnetcenter.com

Page 9 of 24

ASP and Java Script reference

Page 10 of 24

Server Variables The following example dominstrates how to retrieve some of the usefull server variables. <% agent = Request.ServerVariables("http_user_agent") 'Gets the browser type IP = Request.ServerVariables ("REMOTE_ADDR") 'Retrieves the user IP Address dnsIP = Request.ServerVariables("remote_host") 'Retrieves the remote host IP Address serverName = Request.ServerVariables("server_name") 'Retrieves the page domain name referer = request.servervariables("http_referer") 'Retrieves the referer url scriptName=request.servervariables("script_name") 'Retrieves current page serverPort=request.servervariables("server_port") 'Retrieves server port serverSoftware=request.servervariables("server_software") 'Retrieves server software Url=request.servervariables("URL") 'Retrieves page url method=request.servervariables("Request_Method") 'Retrieves request mehtod .. get or post %> <% Response.Write("User Agent: "&agent &"
") Response.Write("IP Address: "&IP &"
") Response.Write("Remote host IP: "&dnsIP &"
") Response.Write("Server Domain name: "&serverName &"
") Response.Write("Referer page: "&referer &"
") Response.Write("Script Name: "&scriptName &"
") Response.Write("Server Port: "&serverPort &"
") Response.Write("Server Sortware: "&serverSoftware &"
") Response.Write("Page url: "&Url &"
") Response.Write("Request Method: "&method &"
") %>

Forms Java script is used to validate forms, display information in text box or when button is clicked, and other nice activities. Form validation means checking that proper information are entered in the form fields before submission. Forms are not of much use in terms of processing and posting when you are limited to HTML and you don't have access to other script such as CGI. This discussion is limited to form validations. If you want learn how create them, check out the html form page. The following example alerts the value entered the text fields:

Type your first name:
Type your last name: http://www.aspnetcenter.com

The only JavaScript concept of this example is OnClick. onClick event handler responds when object is clicked and executes the JavaScript code or function. In this case, it executes alert box . The alert box displays the values in the text boxes. Here is the result of this example: Type your first name: Page 10 of 24

ASP and Java Script reference Page 11 of 24 Type your last name:
The following example explains how to select and display:
Select one: <select name="selec" onchange='alert("You selected "+document.fm2.selec.value)'>


We use onChange event handler, to display alert box with the selected value. OnChange executes the specified JavaScript code or function on the occurance of a change event. In this case, it executes an alert box that displays selected value of the select box. Here is the result of this example: Select one:

Form Validations The most practical business use of java script is object validations. Making sure that the user's information is as it required. This sample is java script code that checks and alerts if the fields of the form are empty. <SCRIPT LANGUAGE=JAVASCRIPT> function validate(formCheck) //Function with a parameter representing a form name. { if (formCheck.name.value =="") { alert("Please provide your name:"); formCheck.name.focus(); return false; } var mail=formCheck.email.value http://www.aspnetcenter.com

How it works We created a function called validate which takes a parameter. This parameter represents the form name. Using if statement, we compare the text field name with empty string. If this field is equal to the empty string, then displayed alert box and set the focus to this field. We then return false to avoid the action to be continued. Email field is slightly different. For this field, we check if Page 11 of 24

ASP and Java Script reference if (mail.indexOf("@.") == -1) { alert("Please type a valid email:"); formCheck.email.focus(); return false; } return true;

Page 12 of 24

}
Your Name:
Your Eamil:


@ and . are provided. If not, we alert the user, set the focus and return false. If the two controls pass true value, then the function returns true. In this case, onClick event handler returns true and nothing happens. Note: If the form action proceeds to another page, use onSubmit instead of onClick. onSubmit executes the function and continues processing the file defined in the form action

Window object refers to the browser and all the items you can see within it. This lecture explains objects to create pop-up window and properties and methods available. As we all ready explained, properties are sub- objects which is part of another object and methods are ways to do things. Javascript window object properties could be some thing like window name, size, address, etc. Javascript window object methods are things like open, close, scroll, move, resize, alert, etc. The least you could have for window is open a blank window. Here is how you open a blank window: window.open() This opens blank window and uses all the default settings. The best way to display a window with particular size, color, menus, toolbars, objects, etc is to create a function and call it when a linke or object is clicked or onload event. The following example is pop-up window that displays another web site in smaller window: <SCRIPT LANGUAGE="javascript"> function windowE() { window.open('http://tek-tips.com/','winE', 'height=400,width=650,toolbar=no') } http://www.aspnetcenter.com

We just created a pop-up window with, height of 400 pixels wide and width of 650 pixels. It displays the web site www.dialtone.com. The name of the window is winE and it will not display a toolbar because we set the toolbar to no. This window is created in function. The only thing appears when this page loads is "click Page 12 of 24

ASP and Java Script reference Page 13 of 24 here" in link. This link calls the function that Click here creates the window. Here is the result: Click here The syntax to remember when creating pop-up window is window.open("url", "windowName", "windowAttributes"). URL you can specify any url, local or foreign. Without a url, blank window will be display. WindowName is the name of the object. WindowAttributes are arguments available such as toolbar, statusbar, scrollbars, etc. Here are list of attributes you can use to customize your pop-up window: width location scrollbars

height directories resizable

toolbar status menubar

The following example uses all the attributes listed above: <script type="text/javascript"> function openwindow() { window.open("http://www.tek-tips.com/","WinC", "toolbar=no,location=no,directories=no, status=no,menubar=no,scrollbars=no,resizable=no, copyhistory=no,width=400,height=400") }


Again this window display web site and sets all attributs to no, which means this window will not display any of those named attributes. Another thing to note is, we using button to call the function that creates the window. Bellow is the result of this example. Click to view it.

The following complete list of properties and methods available for window objects. Property Closed defaultStatus

Description Syntax Returns boolean value to determine if a window.closed window has been closed Defines the default message displayed in a window.defaultStatus(="message") window's status bar

http://www.aspnetcenter.com

Page 13 of 24

ASP and Java Script reference Page 14 of 24 Defines the document to displayed in a document window.document window Returns an array containing references to all frames the named child frames in the current window.frames(="frameId") window history Returns the history list of visited URLs window.history Returns the height of the window's display innerHeight window.innerHeight = value area Returns the width of the window's display innerWidth window.innerWidth = value area length Returns the number of frames in the windowwindow.length location The URL loaded into the window window.location Windows location bar. It has the property locationbar window.locationbar.visible=false visible. Windows menu bar. Alos has visible menubar window.menubar.visible=false property. name Sets or returns window's name window.name The name of the window that opened the opener window.opener current window Returns the height of the outer area of the outerHeight window.outerHeight window Returns the width of the outer area of the outerWidth window.outerWidth window Return the X-coordinate of the current pageXOffset window.pageXOffset window Return the Y-coordinate of the current pageYOffset window.pageYOffset window The name of the window containing this parent window.parent particular window Returns boolean value indicating the personalbar window.personalbar.visible=false visibility of the directories bar Returns boolean value indicating the Scrollbars window.scrollbars.visible=false visibility of the scrollbars bar Self Refers to current window self.method The message displayed in the window's Status window.method="message" status bar Returns boolean value indicating visibility Statusbar window.statusbar.visible=false of the status bar Returns boolean value indicating visibility Toolbar window.toolbar.visible=false of the tool bar Top Returns the name of topmost window window.top Window Returns the current window window.[property]or[method] Method Description Syntax alert(message) Displays text string on a dialog box alert("Type message here") http://www.aspnetcenter.com

Page 14 of 24

ASP and Java Script reference Page 15 of 24 back() Loads the previous page in the window window.back() blur() Removes the focus from the window window.blur() Sets the window to capture all events of a captureEvents() window.captureEvent(eventType) specified type Clears the timeout, set with the setTimeout clearTimeout() window.clearTimeout(timeoutID) method close() Closes the window window.close() Displays a confirmation dialog box with the confirm(message) confirm("type message here") text message disableExternalCapture/ window.disableExternalCapture( )/ Enables/disables external event capturing enableExternalCapture window.enableExternalCapture( ) focus() Gives focus to the window window.focus() forward() Loads the next page in the window window.forward() Invokes the event handler for the specified handleEvent(event) window.handleEvent(eventID) event moveBy(horizontal, Moves the window by the specified amount window.moveBy(HorValue, VerValue) vertical) in the horizontal and vertical direction This method moves the window's left edge moveTo(x, y) and top edge to the specified x and y comoveTo(Xposition,Yposition) ordinates open() Opens a window window.open(url, name, attributes) print() Displays the print dialog box window.print() prompt(message,defaultV window.prompt("type message Displays prompt dialog box alue) here",value) Release any captured events of the specified releaseEvents(event) window.releaseEvents(eventType) type resizeBy(horizantal, Resizes the window by the specified amount window.resizeBy(HorVoue,VerValue) vertical) Resizes the window to the specified width window.resizeTo(widthValue,heightVal resizeTo(width,height) and height ue) Scrolls the window to the supplied coscroll(x, y) window.scroll(xVlue,yValue) ordinates Scrolls the window's content area by the scrollBy(x, y) window.scrollBy(HorVlue,VerValue) specified number of pixels Scrolls the window's content area by the scrollTo(x, y) window.scrollTo(xVlue,yValue) specified number of cordinates setInterval(expression, Evaluates the expression every time window.setIntervals(expression,millise time) milliseconds conds) stop() Stops the windows from loading window.stop() Working Example -Order & Credit card validation Select Pizza Type: Select Toppings: Extra Cheese Price Beef Onion http://www.aspnetcenter.com

Page 15 of 24

ASP and Java Script reference

Page 16 of 24 Pineapple Pepper Anchovy

Payment Method Card Number: Expiration Date: www.clik.to/program

Close | Home Note: This code does not check credit card expiry date. Cancelled or not issued credits cards are still valid and cannot be validated using JavaScript. <script type="text/javascript">
<strong>Select Pizza Type:
<select name="pizzaSize">
<strong>Select Toppings:
Extra Cheese
Beef
Onion
Pineapple
Pepper
Anchovy
<strong>Payment Method
<select name="paymentMethod">

www.clik.to/program

Close this window

Working Example -Validate user & password User Name: Password: <script language="javascript">
Page 20 of 24

ASP and Java Script reference

Page 21 of 24

@ www.clik.to/program or [email protected] */ var invalidChars = "@$!#)(%/~>_<"; function checkPassword() { password=document.form.password.value; user =document.form.user.value; if(user.length<4) { alert("User name must be 4 or more characters"); document.form.user.focus(); return false; } else if(password.length<8) { alert("Password must be 8 or more characters long"); document.form.password.focus(); return false; } for(var i = 0; i < invalidChars.length; i++) { if(password.indexOf(invalidChars.charAt(i)) != -1 || user.indexOf(invalidChars.charAt(i))!=-1) { alert("Please enter valid characters only such as, 1-9, a-z, A-Z"); return false; } } alert("Right information was provided. User name: "+user+"\n Password: "+password); } //--> <Strong>
Working Example -Validate user & password
<Strong>User Name:
<strong>Password:

Close | Home

http://www.aspnetcenter.com

Page 21 of 24

ASP and Java Script reference

Page 22 of 24

Asp code to give every row in ur result list alternate colors : : : Distributed by Nnabike Okaro [email protected] www.datastruct.com <% 'Display results in a table rs.MoveFirst 'counter for row colors i=1 Do While rs.Eof = False 'ur code 'change colors i = cint(i) val = i mod 2 if val = 1 then color="white" else color="lightgrey" end if i = i+1 <% bordercolor="LIGHTGREY"> //ur data <% rs.MoveNext Loop Conn.close %>

VB Script Form Validation Form validation involves checking if the required information is provided by the user. We can make sure to see if a field is empty, figure out type of value provided, count number of characters or value, can check if special character(s) is present and more. Here is a syntax for checking a field value. if form.name.value="" then msgbox"Please enter name". This checks if the name field is empty and informs the user. if len(form.name.value) < 2 or len(form.txtname.value)>50 then msgbox "Too short or too long". This checks if the lenth of the value provided is less than 2 characters or more than 50 characters and if so prompts message. if instr(form.txtemail.value,"@") = 0 then msgbox("Invalid e-mail"). This checks if @ is present and prompts message if not. if (Not (IsNumeric(form.txtage.value)) then msgbox"Invalid age". This check if the value is not numeric and prompts message if so. To check if it's numeric, do not specify NOT before IsNumeric. form.txtage.focus http://www.aspnetcenter.com

Page 22 of 24

ASP and Java Script reference . This put focus in the text box, age. form.txtage.select . This highlights the text in the text box.

Page 23 of 24

The following example is form that validates provided information before it summits. See forms to learning how to do forms. <script language = "vbscript"> sub cmdUserInfo_OnClick() if len(form.txtName.value)<2 or IsNumeric(form.txtName.value)then msgbox("Type a valid name") form.txtName.focus form.txtName.select elseif len(form.txtAge.value) <2 or Not IsNumeric(form.txtAge.value) then msgbox("Type a valid age") form.txtAge.focus form.txtAge.select elseif form.txtEmail.value="" then msgbox("Enter a valid email") form.txtEmail.focus form.txtEmail.select elseif instr(form.txtEmail.value,"@") = 0 then msgbox("Type a valid email") form.txtEmail.focus else msgbox"Success!" end if end sub
Name:
Age:
Email:

Notice we did not call the sub procedure onclick() method. We name the command button cmdUserInfo which is the name of the sub procedure that has the validation code. This is an event driven procedure that evaluates it's code when the command button is clicked. When the button is clicked, if statement checks the name field to make sure 2 characters or more is entered and the values are not numbers. If the name field is ok, then we do the age field same making sure that two numbers are entered. If the name, and age field are ok, then we check the email field to make sure that the @ sign is present. We prompt a proper error message each time that the condition is not true. We use table to make the form objects look friendly. The txt added to the each text field name and cmd added to the button are standard naming convention for visual basic. Here is the result of this example

Page 23 of 24

ASP and Java Script reference = "Summit">


http://www.aspnetcenter.com

Page 24 of 24

Page 24 of 24

Related Documents