How can I add paging for results in a table created in Classic ASP? - vbscript

I have some code done in VBScript that creates a table. Specifically, the code pulls information from a database and then loops through the result adding them to a table. The problem is that there are 14,000 rows in this table. Every time this page tries to load, I get a 500 Internal Server error which I assume is due to lack of memory.
For the loop, I have this:
<%
fHideNavBar = False
fHideNumber = False
fHideRequery = False
fHideRule = False
stQueryString = ""
fEmptyRecordset = False
fFirstPass = True
fNeedRecordset = False
fNoRecordset = False
tBarAlignment = "Left"
tHeaderName = "DataRangeHdr1"
tPageSize = 0
tPagingMove = ""
tRangeType = "Text"
tRecordsProcessed = 0
tPrevAbsolutePage = 0
intCurPos = 0
intNewPos = 0
fSupportsBookmarks = True
fMoveAbsolute = False
If IsEmpty(Session("DataRangeHdr1_Recordset")) Then
fNeedRecordset = True
Else
If Session("DataRangeHdr1_Recordset") Is Nothing Then
fNeedRecordset = True
Else
Set DataRangeHdr1 = Session("DataRangeHdr1_Recordset")
End If
End If
If fNeedRecordset Then
Set DataConn = Server.CreateObject("ADODB.Connection")
DataConn.Open "DSN=MYDSN","MyUserName","MyPassword"
Set cmdTemp = Server.CreateObject("ADODB.Command")
Set DataRangeHdr1 = Server.CreateObject("ADODB.Recordset")
cmdTemp.CommandText = "SELECT PHONE, FAX, FIRM, ID FROM NNYBEA ORDER BY ID"
cmdTemp.CommandType = 1
Set cmdTemp.ActiveConnection = DataConn
DataRangeHdr1.Open cmdTemp, , 0, 1
End If
On Error Resume Next
If DataRangeHdr1.BOF And DataRangeHdr1.EOF Then fEmptyRecordset = True
On Error Goto 0
If Err Then fEmptyRecordset = True
If Not IsEmpty(Session("DataRangeHdr1_Filter")) And Not fEmptyRecordset Then
DataRangeHdr1.Filter = Session("DataRangeHdr1_Filter")
If DataRangeHdr1.BOF And DataRangeHdr1.EOF Then fEmptyRecordset = True
End If
If fEmptyRecordset Then
fHideNavBar = True
fHideRule = True
End If
Do
If fEmptyRecordset Then Exit Do
If Not fFirstPass Then
DataRangeHdr1.MoveNext
Else
fFirstPass = False
End If
If DataRangeHdr1.EOF Then Exit Do
%>
<tr>
<td><p align="center"><%= DataRangeHdr1("FIRM") %></td>
<td><p align="center"><%= DataRangeHdr1("PHONE") %></td>
<td><p align="center"><%= DataRangeHdr1("FAX") %></td>
<%end if%>
</tr>
<%
Loop%>
Now, I believe that the programmer before me essentially copied the code from this website: http://www.nnybe.com/board%20members/DEFAULT.ASP
In fact, I actually changed the column names in my loop to match the website, since it was so similar (my real column names are different). After the loop, the code I have is as follows:
</TABLE>
<%
If tRangeType = "Table" Then Response.Write "</TABLE>"
If tPageSize > 0 Then
If Not fHideRule Then Response.Write "<HR>"
If Not fHideNavBar Then
%>
<TABLE WIDTH=100% >
<TR>
<TD WIDTH=100% >
<P ALIGN=<%= tBarAlignment %> >
<FORM <%= "ACTION=""" & Request.ServerVariables("PATH_INFO") & stQueryString & """" %> METHOD="POST">
<INPUT TYPE="Submit" NAME="<%= tHeaderName & "_PagingMove" %>" VALUE=" << ">
<INPUT TYPE="Submit" NAME="<%= tHeaderName & "_PagingMove" %>" VALUE=" < ">
<INPUT TYPE="Submit" NAME="<%= tHeaderName & "_PagingMove" %>" VALUE=" > ">
<% If fSupportsBookmarks Then %>
<INPUT TYPE="Submit" NAME="<%= tHeaderName & "_PagingMove" %>" VALUE=" >> ">
<% End If %>
<% If Not fHideRequery Then %>
<INPUT TYPE="Submit" NAME="<% =tHeaderName & "_PagingMove" %>" VALUE=" Requery ">
<% End If %>
</FORM>
</P>
</TD>
<TD VALIGN=MIDDLE ALIGN=RIGHT>
<FONT SIZE=2>
<%
If Not fHideNumber Then
If tPageSize > 1 Then
Response.Write "<NOBR>Page: " & Session(tHeaderName & "_AbsolutePage") & "</NOBR>"
Else
Response.Write "<NOBR>Record: " & Session(tHeaderName & "_AbsolutePage") & "</NOBR>"
End If
End If
%>
</FONT>
</TD>
</TR>
</TABLE>
<%
End If
End If
%>
</TABLE>
I'm guessing from the < and > around the PagingMove part, this is supposed to allow paging. However, I'm not even seeing this on my page. I don't know if the code on the link above works on their website, but for my own website I'd ask:
How can I modify this code to provide an option to click through pages of the data result so the server doesn't run out of memory?
If there is a more elegant solution to this that can accomplish the same thing, I'd appreciate that as well!!!

In your SQL you could add a LIMIT offset
SELECT PHONE, FAX, FIRM, ID FROM NNYBEA ORDER BY ID LIMIT 0,10 ' Results 1 to 10
SELECT PHONE, FAX, FIRM, ID FROM NNYBEA ORDER BY ID LIMIT 10,10 ' 11 - 20
SELECT PHONE, FAX, FIRM, ID FROM NNYBEA ORDER BY ID LIMIT 20,10 ' 21 - 30
...
If you're using MySQL you can use...
SELECT SQL_CALC_FOUND_ROWS PHONE, FAX, FIRM, ID FROM NNYBEA ORDER BY ID LIMIT 0,10
... to get a total count of the results and calculate the number of page links to display:
(total_results/results_per_page) ' and round up.
Then link to the pages below the results table and pass the page numbers as a query string:
default.asp?page=1
default.asp?page=2
default.asp?page=3
...
Have some code at the top of your page that gets the requested page number and calculates the correct offset value:
<%
Const results_per_page = 10
Dim limit_offset, page_num
limit_offset = 0 ' default
page_num = request.querystring("page")
if isNumeric(page_num) then
page_num = int(page_num)
if page_num > 0 then
limit_offset = (page_num-1)*results_per_page
else
page_num = 1 ' default
end if
else
page_num = 1 ' default
end if
%>
Finally, apply the limit offset to your SQL:
cmdTemp.CommandText = "SELECT PHONE, FAX, FIRM, ID FROM NNYBEA ORDER BY ID LIMIT " & limit_offset & "," & results_per_page
You could also use GetRows() to convert the recordset to a 2D array and apply a limit when looping
Dim r, rs_loops, theData
theData = DataRangeHdr1.getRows()
rs_loops = page_num*results_per_page
if rs_loops > uBound(theData,2) then rs_loops = uBound(theData,2)
for r = limit_offset to rs_loops
' output data from the DataRangeHdr1 recordset
%>
<tr>
<td><p align="center"><%= theData(2,r) ' firm %></td>
<td><p align="center"><%= theData(0,r) ' phone %></td>
<td><p align="center"><%= theData(1,r) ' fax %></td>
</tr>
<%
next
But this would mean storing large amounts of unseen data in memory. Using a LIMIT offset in the SQL would make more sense.

Related

ASP Classic Code Logic using If statements to check inputs from a form

I have this code in an ASP page written 20+ years ago. I am trying to update the code an I am having trouble figuring this out:
If Request("SUTyp").Count > 1 THEN
CountCriteria = 0
For intMulti=1 to Request("SUTyp").Count
If Request("SUTyp")(intMulti) <> "*" Then
CountCriteria = CountCriteria + 1
If CountCriteria = 1 Then
SUTypCode = "((tblSU.SUTypCode) LIKE '" & Request("SUTyp")(intMulti) & "')"
Else
SUTypCode = SUTypCode & " OR ((tblSU.SUTypCode) LIKE '" & Request("SUTyp")(intMulti) & "')"
End If
Else
SUTypCode = ""
intMulti = Request("SUTyp").Count
End If
SUTyp is a variable that is coming from a form on the previous page. There is an option (from that previous page) in the select box on the form to 'Select All' or to 'Select Multiple Options'.
<Select name="SUTyp" Size="7" Multiple >
<OPTION VALUE="*" SELECTED>all study unit types
<%
do while (not rsSUType.eof) and (SaveError <> -2147467259)
if rsSUType.Fields("SUTypCode").Value = "*" then
%>
<OPTION VALUE="<%response.write(rsSUType.Fields("SUTypCode").Value)%>" SELECTED>.
<%response.write(rsSUType.Fields("SUTypCode").Value)%>,
<%response.write(rsSUType.Fields("SUTyp").Value)%>
<%
Else
%>
<OPTION VALUE="<%response.write(rsSUType.Fields("SUTypCode").Value)%>">.
<%response.write(rsSUType.Fields("SUTypCode").Value)%> -
<%response.write(rsSUType.Fields("SUTyp").Value)%>
<%
End If
rsSUType.movenext
loop
%>
</Select>
It is then using some data to create a variable (SUTypCode =) for a WHERE clause to query the database. What I don't know is the logic of what it is saying. Specifically:
For intMulti=1 to Request("SUTyp").Count
If Request("SUTyp")(intMulti) <> "*" Then
CountCriteria = CountCriteria + 1
If CountCriteria = 1 Then
SUTypCode = "((tblSU.SUTypCode) LIKE '" & Request("SUTyp")(intMulti) & "')"
I am guessing that somehow the ASP form sets some kind of variable intMulti and uses that for a comparison.
If someone could shed some light on this and so I can re-write it that would be great. This is being created using PHP, so I am just trying to figure out what this means so I can create the equivalent.
Thanks!

Adding a text area in table and saving it to SQL Server database

I'm using Classic ASP to add a note function to the table that is displaying rows from a database. The inserted row will save to the database saved Remarks but the following code isn't working.
<%
Dim fRemark
fRemark = Request.Form("Remarks")
Dim rsIntra,MyQryItr2
set cnIntra = Server.CreateObject("ADODB.Connection")
set MyQryItra2 = server.CreateObject ("ADODB.Recordset")
set rsIntra = Server.CreateObject("ADODB.Recordset")
MyQryItra2 = "select Remarks from [PurchaseOrderTrackInfo]"
rsIntra.Open MyQryItra,strRMSIDMcn
if rsIntra.eof then
MyQryItr2 = "insert into [PurchaseOrderTrackInfo] Remarks values N'" & fRemark & " '; "
cast(Remarks as int)
cnIntra.Execute MyQryItr2
else
rsIntra.close
set rsIntra = Nothing
set rsIntra = server.CreateObject("ADODB.Recordset")
MyQryItr2 = "UPDATE [PurchaseOrderTrackInfo] SET Remarks = N'" & fRemark & " '; where Remarks = rowID;"
end if
set rsIntra=Nothing
strConnDB= "Driver={SQL Server};Server=GB;Database=PurchaseOrderTrackInfo;UID=madfox;PWD=;"
%>
<td colspan="10" bordercolor=#3399ff bgcolor=#FFFF99 align="center">
<font face="Arabic Transparent" size="1" color="#800080"></font>
<form action=UpdatePO1.asp method=post >
<textarea name="Remarks" cols="20" rows="2" ><%=fRemark%></textarea>
<input type="submit" class="btn1" value="save" name="finish"/>
<input type="hidden" name="rowID" value="ID" />
</td>
</form>
<%
you never execute your update query. also your update statement does not seem to be valid as you are using the column Remarks as storage for the Remark and as row id. consider adding a rowid column to you table and use the following update statement
MyQryItr2 = "UPDATE [PurchaseOrderTrackInfo] SET Remarks = N'" & fRemark & " ' where rowId =" & rowID
cnIntra.Execute MyQryItr2
Since your code is vulnerabe to SQL injection, you should look up parameterized queries.

How to show sub categories under main category

I need some help on classic ASP.
Currently, the output shows like:
cat
south
cat
south
cat2
east
cat2
west
I don't want to see the main categories repeating like that.
How do I combine main category into one and show sub categories below main?
Like:
cat
south
south
cat2
east
west
Category table
ID Category
------------
01 cat
02 cat2
03 cat3
Subcat table
ID Subcat Category_id
-------------------------
1 south 01
2 north 01
3 east 02
4 west 02
5 line 03
Code:
<%
sSQL = " SELECT s.*, c.* FROM Category c, Subcat s WHERE s.Subcat_id = c.Subcat_id "
objRS.Open sSQL, objCon
response.Write sSQL
Do Until objRS.EOF
sCategory = objRS("Category")
sSubcat = objRS("Subcat")
%>
<input type="text" name="CategoryN" size="40" maxlength="50" value="<%= sCategory %>"><br />
<input type="text" name="SubcatN" size="40" maxlength="50" value="<%= sSubcat %>"><br />
<%
objRS.MoveNext
Loop
objRS.Close
%>
Thanks very much!
Something like this:
<%
currCat = "~~~~~~"
sSQL = "SELECT s.*, c.* FROM Category c, Subcat s WHERE s.Subcat_id = c.Subcat_id "
objRS.Open sSQL, objCon
response.Write sSQL
Do Until objRS.EOF
sCategory = objRS("Category")
sSubcat = objRS("Subcat")
if currCat <> sCategory Then
currCat = sCategory
<%
<input type="text" name="CategoryN" size="40"
maxlength="50" value="<%=sCategory%>"><br />
%>
End If
%>
<input type="text" name="SubcatN" size="40"
maxlength="50" value="<%= sSubcat %>"><br />
<%
objRS.MoveNext
Loop
objRS.Close
%>

Classic ASP Intentional Wait / Delay inside Loop with Buffer Flushing

We have a script that sends emails and we want an intentional wait for n milliseconds between messages to not flood the server. The asp_Wait() I found works but without any output. That is, when the script is completely done running it dumps to the page.
My goal is to view each line in a browser as it is executed so I can monitor the progress of the script.
I have tried both with buffering ON and OFF with the same curious result (Server 2008 R2, IIS7). A test loop demonstrates this with a 1-second delay in the loop it will take n seconds to load the page, and I am putting Now() on each line to see when that loop executing (proving the wait is working), but I do not see a single line outputted during the script's execution.
<%
Dim IsBuffer ' this allows easy toggling of the buffer feature
IsBuffer = False
If IsBuffer Then Response.Buffer = True End If
Server.ScriptTimeout=7200 ' 2 hours (yes this is overkill!!)
i = 0
Response.Write "<h2>Test Page</h2><hr>"
If IsBuffer Then Response.Flush() End If ' flush the header
while i < 20
i = i + 1
Response.Write i & " at: " & Now() & "<br />" & VbCrLf
If IsBuffer Then Response.Flush() End If
Call asp_Wait(1000) ' milliseconds
wend
Response.Write "<br /><strong>**TOTAL OF " & i & " LOOPS.**</strong><br />" & vbCrLf
Sub asp_Wait(nMilliseconds)
Dim oShell
Set oShell= Server.CreateObject("WScript.Shell")
Call oShell.run("ping 1.2.3.4 -n 1 -w " & nMilliseconds,1,TRUE)
End Sub
%>
Thanks for your help!
I believe the default configuration for IIS7 enables GZIP compression. With compression enabled, ASP tends to ignore Response.Flush() statements.
Try following the instructions here to disable compression and see if that helps.
Edit: Found this as well.
I like to let the client handle delays by using redirect to a page that looks like this:
<%
ID_template= request.querystring("ID_template")
s_resume=request.querystring("resume")
s_file = "admin_email_send_go.asp?ID_template=" & ID_template
if (s_resume="yes") then s_file = "admin_email_send_resume.asp?ID_template=" & ID_template
%>
<html>
<head>
<meta http-equiv="Refresh" content="<%=int(session("n_records")/50)%>; url=<%=s_file%>">
<script type="text/javascript">
<!--
function delayer(){
document.location = "<%=s_file%>"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()',<%=int(session("n_records")*20)%>)" bgcolor='#FFFFFF'>
<br>
<table width='100%' height='100%'>
<tr>
<td valign=middle align=center>
<table border=1>
<tr>
<td>
Total list size: <%=session("n_records")%><br>
Sent so far: <%=session("n_records_sent")%>
</td>
</tr>
</table><br>
<br>
Sending next group of <%=application("email_group_size")%> in 2 seconds.<br>
Please wait...<br>
<br>
If you want to quit or pause the process at any time, click <a href='admin_email_send.asp?ID_template=<%=ID_template%>'>here</a>.<br>
<br>
</td>
</tr>
</table>
</body>
</html>
This code worked best for me:
<%
Private Function Delay(intSeconds)
StartTimed = Now()
CurrentTimed = Now()
While DateDiff("s",StartTimed,CurrentTimed) < intSeconds
CurrentTimed = Now()
Wend
End Function
Response.Write("This is now<br>")
call Delay(10)
Response.Write("This is 10 seconds later<br>")
%>

Latest images uploaded coding problem

anyone could help me understand the following asp.net 2.0 coding?
It is supposed to show me a couple of the latest photos i uploaded to a particular folder in the photoalbum.
however when i upload a new file in an folder which already has images... the images that show up when using the code is the first images in this folder...
and sometimes nothing shows up...
<%
latestfolder = "na"
latestdate = cdate("01/01/09")
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fo=fs.GetFolder(Server.MapPath("images/gallery"))
for each folder in fo.subfolders
if cdate(folder.DateLastModified) > latestdate then
latestdate = cdate(folder.DateLastModified)
latestfolder = folder.name
end if
next
if latestfolder <> "na" then
set fi=fs.GetFolder(Server.MapPath("images/gallery/" & latestfolder))
looptimes = 0
for each file in fi.files
if month(file.DateLastModified) = month(latestdate) then
if right(lcase(file.Name),3) = "jpg" then %>
<a href="thumbnail.aspx?picture=<%=server.URLEncode("images/gallery/" & latestfolder & "/" & file.Name)%>&maxWidth=640&maxHeight=480" target="_blank" style="text-decoration:none; cursor:pointer;">
<img src="thumbnail.aspx?picture=<%=server.URLEncode("images/gallery/" & latestfolder & "/" & file.Name)%>&maxWidth=100&maxHeight=60" style="border:1px solid #ffffff; margin:5px; margin-top:14px;">
</a>
<% end if
end if
looptimes = looptimes + 1
if looptimes = 6 then exit for end if
next
end if
%>
hope some can help me :)
Looks like the following code is picking up all JPEG files for the current month:
if month(file.DateLastModified) = month(latestdate) then
if right(lcase(file.Name),3) = "jpg" then%>
...
<% end if
end if
when it loops through the files, it checks whether the last modified date of the image matches the last modified date of the folder. that is the original coders definition of "a couple of the latest photos" for that album. it also makes sure that there's never more than 6.
If you don't upload photos all too often, you could easily end up with just one photo every time. If you don't get any photos out of it at all, you've probably done something else in that folder, that would've changed its last modified date, without adding any photos.
I'd consider getting rid of the month criteria, and just stick with the 6 photos limit, i.e. replace
if month(file.DateLastModified) = month(latestdate) then
if right(lcase(file.Name),3) = "jpg" then %>
<a href="thumbnail.aspx?picture=<%=server.URLEncode("images/gallery/" & latestfolder & "/" & file.Name)%>&maxWidth=640&maxHeight=480" target="_blank" style="text-decoration:none; cursor:pointer;">
<img src="thumbnail.aspx?picture=<%=server.URLEncode("images/gallery/" & latestfolder & "/" & file.Name)%>&maxWidth=100&maxHeight=60" style="border:1px solid #ffffff; margin:5px; margin-top:14px;">
</a>
<% end if
end if
with
if right(lcase(file.Name),3) = "jpg" then %>
<a href="thumbnail.aspx?picture=<%=server.URLEncode("images/gallery/" & latestfolder & "/" & file.Name)%>&maxWidth=640&maxHeight=480" target="_blank" style="text-decoration:none; cursor:pointer;">
<img src="thumbnail.aspx?picture=<%=server.URLEncode("images/gallery/" & latestfolder & "/" & file.Name)%>&maxWidth=100&maxHeight=60" style="border:1px solid #ffffff; margin:5px; margin-top:14px;">
</a>
<% end if

Resources