Code required for learning ASP Programming

Source: Internet
Author: User
Tags servervariables

The program design I learned in ASP class is based on the syntax and object. At the end of programming, I cannot figure out how to combine it to complete a module, the following describes how to combine these syntaxes according to the commonly used modular methods of programmers. Please remember these syntaxes according to the module and apply them according to the module. You do not have to memorize them one by one, the key is that these modules can be used accurately, take them out, and install them!

Note that all of the following punctuation marks are English halfwidth symbols. If you write them as fullwidth, they will not be able to run. Do not avoid them ......

1. Common writing
(1) Asp start Terminator Syntax: <%> file suffix. asp
(2) request. Form ("title") 'obtains the value of title in an input box of the form.
(3) request. querystring ("title") 'gets the value after the title = parameter in the connection.

(4) dim Str
STR = "I love you"
Response. Write (STR) 'to screen output
(5) response. Write "OK, the program is running here! "

(6) SQL = "select * from news"
Response. Write SQL
'Debugging and checking whether SQL statements are correctly written are commonly used

(7) response. Redirect ("login. asp") 'jump to another page
(8) response. Redirect ("Admin. asp") 'to the background
(9) The response. End program output ends, and the content below this statement is not displayed.
(10) response. Write ("<SCRIPT> alert ('???! ') </SCRIPT> ")' the prompt window is displayed.

2. Judgment statement
(1) check whether the user name and password sent from the form are correct and prompt
If request ("username") = "admin" then
Response. Write "Congratulations, you have logged on successfully"
Else
Response. Write "sorry, the user name you entered is incorrect. Please return and re-enter"
End if

(2) If both the user name and password are correct, they will be transferred to the background; otherwise, they will be returned to the new input page.
If request ("name") = "admin" and request ("pass") = "admin" then
Response. Redirect "Admin. asp"
Else
Response. Redirect "login. asp"
End if

(3) Use the variable value and string value together &
A = "I"
B = "love"
C = "you"
Response. Write A & B & C & "Mom"

3. Loop statement: displays records in six databases cyclically.
(1) Statement 1:
Do while not Rs. EOF
Response. Write "<br> <font color = #000000>" & RS ("title") & "</font> <br>"
Rs. movenext
Loop
(2) Statement 2:
For n = 1 to 6
Response. Write RS ("title") & "<br>"
If Rs. EOF then
Exit for 'jump out of the For Loop
Else
Rs. movenext move one record set down
End if
Next

4. Common variable conversion functions
Now () function returns the system time
The date () function returns the current system date.
The CSTR (INT) function converts an expression to a string.
CINT (string) converts an expression to a numeric type
Trim (Request ("username") function removes spaces around the string
Left (RS ("title"), 10 )&"... "The function returns the first 10th characters (including the nth length) on the left of the string. This function is generally used to limit the display length of a news title.
The LEN (string) function returns the length of a string. The length of a Chinese character is also counted as one.
Request. servervariables ("remote_host ")'
Mid (STR, start character, [read length]): intercept the middle substring of the string
Right (STR, nlen): truncates the nlen length substring from the right.
Lcase (STR): converts a string to lowercase.
Ucase (STR): converts a string to uppercase.
Ltrim (STR): removes spaces on the left of the string.
Rtrim (STR): removes spaces on the right of the string
Replace (STR, search string, replace string, [Starting character, replacement times, comparison method]):
Replace string
Note: Default Value: Start character 1; unlimited number of replacements; Case sensitivity (0)
Instr ([start character,] STR, search string [, comparison method]): checks whether a sub-string contains optional parameters. You must select the return start position at the same time.

5. Access database connection code
(1) Method 1:
DB = "mydata. mdb" 'if it is stored in the directory, enter "database/mydata. mdb"
Set conn = server. Createobject ("ADODB. Connection ")
Cserver. mappath (db)
Conn. Open connstr

(2) Method 2:
'If your server adopts an older version of the access driver, use the following connection method:
DB = "mydata. mdb" 'if it is stored in the directory, enter "database/mydata. mdb"
Set conn = server. Createobject ("ADODB. Connection ")
C & server. mappath (db)
Conn. Open connstr

6. standard SQL statements and common methods for ASP operations
Including retrieving all records
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from news"
Rs. Open sqlstr, Conn, 'Run the SQL statement and put the data into the RS object.

Select several data entries
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select top 6 * from news"
Rs. Open sqlstr, Conn, 'Run the SQL statement and put 6 pieces of data into the RS object.

Select the value of the ID field in a specified table.
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from news where id =" & request ("ID ")
Rs. Open sqlstr, Conn, 'Run the SQL statement and put 6 pieces of data into the RS object.

Obtain the data transmitted from a form and add it to a table.
Dim a, B, c, d
A = request. Form ("")
B = request ("B ")
C = request ("C ")
D = request ("D ")
Sqlstr100000 = "insert into huiyuanbiao (yonghuming, Mima, Wenti, Daan) values ('" & A & "', '" & B &"', '"& C &"', '"& D &"')"
Conn.exe cute sqlstr100000
Response. Write "congratulations, new data has been added! "

Modify the value of the ID field in a specified table and replace it with the data passed in the form.
Dim A, D, E
A = request ("ID ")
D = request. Form ("D ")
E = request. Form ("e ")
Sqlstr = "Update huiyuanbiao set yonghuming = '" & D & "', Mima = '" & E & "'where id =" &
Response. Write sqlstr
Conn.exe cute sqlstr
Response. Write "congratulations, data modification successful! "

Deletes the value of the ID field in a specified table.
Dim
A = request ("delid ")
Sqlstr = "delete from huiyuanbiao where id =" &
Conn.exe cute sqlstr
Response. Write "congratulations, deletion successful! "

7. Common Methods for operating databases using recordset objects and ASP
(1) use SQL statements to retrieve all data in the News table and put it in RS, sorted by database by default.
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from news"
Rs. Open sqlstr, Conn, 1, 1

(2) extract the first six pieces of data from the news table and put them in RS. Sort the data by default in the database.
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select top 6 * from news"
Rs. Open sqlstr, Conn, 1, 1

(3) display data in six Rs objects cyclically, and display the list

Writing without connection
For n = 1 to 6
Response. Write RS ("title") & "<br>"
If Rs. EOF then
Exit
Else
Rs. movenext
End if
Next

Write method with connection
For n = 1 to 6
Response. Write "<a href = show. asp? Id = RS ("ID")> "& left (RS (" title "), 20) &" </a> <br>"
If Rs. EOF then
Exit
Else
Rs. movenext
End if
Next

(4) Add a data code to the database
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from news"
Rs. Open sqlstr, Conn, '. Note that 1 and 3 indicate the data tables that can be written.
Rs. addnew
RS ("title") = trim (request. Form ("title "))
RS ("neirong") = request. Form ("neirong ")
RS ("date") = now ()
Rs. Update' truly writes data to the database

(5) modify the code of a record and pass the id value through the connection in (2 ).
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from news where id =" & request ("ID ")
Rs. Open sqlstr, Conn, '. Note that 1 and 3 indicate the data tables that can be written.
RS ("title") = trim (Request ("title "))
RS ("neirong") = request ("neirong ")
RS ("date") = now ()
Rs. Update' truly writes data to the database

(6) Delete a record in the database and pass the id value of the data through the connection.
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from news where id =" & request ("ID ")
Rs. Open sqlstr, Conn, '. Note that 1 and 3 indicate the data tables that can be written.
Rs. delete'delete the data.

8. When you click the button, which file does the data carried by the form be transmitted?

<Form method = "Post" Action = "addsave. asp">
<Input type = "text" name = "A">
<Input type = "text" name = "B">
<Input type = "Submit" name = "Submit" value = "Submit">
</Form>

9. Code for receiving and displaying the data submitted by the form on the screen
Response. Write Request. Form ("")
Response. Write now ()
Response. Write trim (request. Form ("B "))

10. Use the application object as the counter syntax

Add in the webpage Header
Application. Lock
Application ("counter") = Application ("counter") + 1
Application. Unlock
Add the following statement to the page where the counting content is to be displayed
Response. Write application ("counter ")

11. Use the session object to protect Admin. asp on the background management page to prevent unauthorized users from accessing

Step 1: Add the following code to the header of all webpages whose website background webpage requires permission protection,
If SESSION ("admin") <> "OK" then
Response. Redirect "login. asp"
Response. End
End if

Step 2: Enter the user name and password verification standard in the detection form on the website background login page
Admname = request. Form ("name ")
Admpass = request. Form ("pass ")
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select * from Admin where name = '" & admname & "' and pass = '" & admpass &"'"
Rs. Open sqlstr, Conn, 1, 3

If Rs. EOF and Rs. bof then
Response. Redirect ("login. asp ")
Response. End
Else
Session ("admin") = "OK"
Response. Redirect ("Admin. asp ")
Response. End
End if

12. Paging code
SQL = "select ........................ Omitting the SQL statement for retrieving all data from the table
Set rs = server. Createobject ("ADODB. recordset ")
Rs. Open SQL, Conn, 1, 1
If not Rs. EOF then
Pages = 30' defines the number of records displayed per page
Rs. pagesize = pages defines the number of records displayed on each page
Allpages = Rs. pagecount calculate the total number of pages that can be divided.
Page = request. querystring ("page ")'
'If statement is a basic troubleshooting method
If isempty (PAGE) or CINT (PAGE) <1 then
Page = 1
Elseif CINT (PAGE)> allpages then
Page = allpages
End if
Rs. absolutepage = page
Do while not Rs. EOF and pages> 0
'Output the content you want ..................
Pages = pages-1
Rs. movenext
Loop
Else
Response. Write ("the database has no content! ")
End if
Rs. Close
Set rs = nothing
'Page number connection and jump page number programs
<Form action = "" method = "get">
<%
If page <> 1 then
Response. Write "<a href =? Page = 1> page 1 </a>"
Response. Write "<a href =? Page = "& (page-1) &"> previous page </a>"
End if
If page <> allpages then
Response. Write "<a href =? Page = "& (page + 1) &"> next page </a>"
Response. Write "<a href =? Page = "& allpages &"> last page </a>"
End if
%>
Number of input pages: <input type = "text" name = "page" size = "3"> Number of pages: <font color = "red"> <% = Page %>/<% = allpages %> </font>
</Form>
13. Code for displaying images and product names in the branch column (4 columns x 3 = 12)
<%
Set rs = server. Createobject ("ADODB. recordset ")
Sqlstr = "select Top 12 * From myproduct"
Rs. Open sqlstr, Conn, 1, 1
I = 1
%>
<Table width = "90%" border = "1" cellspacing = "0" sellpadding = "0">
<Tr>
<%
Do while not Rs. EOF
%>
<TD align = "center">
<br>
<% = RS ("productname") %>
</TD>
<% If I mod 4 = 0 then response. Write "</tr> <tr>"
I = I + 1
Rs. movenext
Loop
Rs. Close
%>
</Tr>
</Table>

14. ACCESS-SQLSERVER of ASP database connection
<%
Issqldata = 0' defines the database category. 0 indicates the ACCESS database, and 1 indicates the SQL database.
If issqldata = 0 then
Access Database
Datapath = "Data/" relative path of the database directory
Datafile = "data. mdb" database file name
C & server. mappath ("" & datapath & "" & datafile &"")
C & server. mappath ("" & datapath & "" & datafile & "") & "; driver = {Microsoft Access Driver (*. mdb )};"
Else
SQL database
Sqllocalname = "(local)" connection IP Address [local IP Address used outside China]
Sqlusername = "sa" username
Sqlpassword = "1" User Password
Sqldatabasename = "data" Database Name
C & sqlusername & "; Password =" & sqlpassword & "; initial catalog =" & sqldatabasename & "; Data Source =" & sqllocalname &";"
End if
On Error resume next
Set conn = server. Createobject ("ADODB. Connection ")
Conn. Open connstr
If err then
Err. Clear
Set conn = nothing
Response. Write "database connection error. Check the connection string. "
Response. End
End if
%>

<! -- Determine whether the website is qualified and handle it -->
<%
Url = trim (request. Form ("url "))
If left (URL, 7) <> "http: //" then
Url = "http: //" & URL
End if
%>

<! -- Display time is a few months and days and processing -->
<%
Y = month (date ())
R = Day (date ())
If Len (y) = 1 then Y = "0" & Y
If Len (R) = 1 then r = "0" & R
Response. Write Y & "month" & R & "day"
%>

<! -- Restrict some IP addresses to access the website -->
<%
Url_str = request. servervariables ("remote_addr ")
Url = Split (url_str ,".")
If URL (0) = 127 and URL (1) = 0 and URL (2) = 0 and URL (3)> 0 and URL (3) <256 then
Else
Response. Write (url_str)
End if
%>

<! -- Set the document display format -->
<%
Function htmlencode (fstring)
If not isnull (fstring) then
Fstring = Replace (fstring, ">", "> ")
Fstring = Replace (fstring, "<", "<")
Fstring = Replace (fstring, CHR (32 ),"")
Fstring = Replace (fstring, CHR (9 ),"")
Fstring = Replace (fstring, CHR (34 ),""")
Fstring = Replace (fstring, CHR (39 ),"'")
Fstring = Replace (fstring, CHR (13 ),"")
Fstring = Replace (fstring, CHR (10) & CHR (10), "</P> <p> ")
Fstring = Replace (fstring, CHR (10), "<br> ")

Htmlencode = fstring
End if
End Function
%>

1. asp and Access database connection:
<%
Dim Conn, mdbfile
Mdbfile = server. mappath ("database name. mdb ")
Set conn = server. Createobject ("ADODB. Connection ")
Conn. Open "driver = {Microsoft Access driver
(*. Mdb)}; uid = admin; Pwd = Database Password; DBQ = "& mdbfile
%>
2. ASP and SQL database connection:
<%
Dim Conn
Set conn = server. Createobject ("ADODB. Connection ")
Con. Open "provider = sqloledb; Data
Source = SQL server name or IP address; uid = sa; Pwd = Database Password; database = Database Name
%>

Create a record set object:

Set rs = server. Createobject ("ADODB. recordset ")
Rs. Open SQL statement, Conn, 3, 2

3. Common SQL commands:
(1) Data Record Filtering:
SQL = "select * from data table where field name = Field Value Order by field name [DESC]"
SQL = "select * from data table where field name like '% Field Value %' order by field name [DESC]"
SQL = "select top 10 * from data table where field name order by field name [DESC]"
SQL = "select * from data table where field name in ('value 1', 'value 2', 'value 3 ')"
SQL = "select * from data table where field name between value 1 and value 2"

(2) update data records:
SQL = "update data table set field name = field value where condition expression"
SQL = "update data table set field 1 = value 1, Field 2 = value 2 ...... Field n = value n where condition expression"

(3) Delete data records:
SQL = "delete from data table where condition expression"
SQL = "delete from data table" (delete all data table Records)

(4) add data records:
SQL = "insert into data table (Field 1, Field 2, Field 3 ...) Values (value 1, value 2, value 3 ...) "
SQL = "insert into target data table select * from source data table" (add records of source data table to target data table)

(5) statistical functions of data records:
AVG (field name) returns the average value of a table column
Count (* | field name) statistics on the number of data rows or the number of data rows with values in a column
Max (field name) obtains the maximum value of a table column.
Min (field name) obtains the minimum value of a table column.
Sum (field name) adds the values in the data column
The method for referencing the above functions:
SQL = "select sum (field name) as Alias from data table where condition expression"
Set rs = conn. excute (SQL)
Use RS ("alias") to obtain the calculation value. Use the same method for other functions.

(6) Create and delete data tables:
Create Table data table name (Field 1 type 1 (length), Field 2 type 2 (length )...... )

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/okfei/archive/2009/08/14/4446718.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.