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

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.

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!

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

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.

ASP script tags involving buttons within HTML

Have a question regarding scripts I've never worked on before. I am trying to get rid of two buttons that seem to be involved in the same script. Inside the body tags, I try to get rid of anything inside of the script, it'll break the page. Tried to do some research on it, but no luck.
This is inside the scripts section
HI, this is the section inside of the body tags
catid = Request.QueryString("id")
sub productInfo(connObj,category)
sqlCustomer = "SELECT * FROM qryProdsCategory WHERE ccategory = '" & Cint(category) & "'"
Set rs = Server.CreateObject ("adodb.Recordset")
rs.Open sqlCustomer, dbc, adOpenDynamic, adLockOptimistic, adCmdText
if not rs.EOF then
if Session("sort")="0" then
rs.sort = "cname ASC"
end if
while not rs.EOF
If rs("stock")="1" then
Response.Write "<form action="&q&Application("secureurl")&"/cart/view-cart.asp"&q&" method="&q&"POST"&q&" name=form"&i&">"
Response.Write "<a href=""product.asp?id=" & rs("catalogID") & ""
Response.Write "" & rs("catalogID") & "" & rs("manModNum") & "</font></td><td width=""18%"" rowspan=""2"">"
Response.Write "<input type="&q&"hidden"&q&" name="&q&"fproductid"&q&" value="&q & rs("catalogID")& q&">"
Response.Write "<input type="&q&"hidden"&q&" name="&q&"fquantity"&q&" value=1>"
Response.Write "<input type="&q&"hidden"&q&" name="&q&"fcat"&q&" value=" & rs("ccategory") & ">"
If rs("stock")="" then
Response.Write "<button class=""btn"" TYPE=""btn"" style=""background-color: #cb0000;color: #fff;"">.</button> </form>"
Else
Response.Write "<button "">ADD</button></form>"
End If
End If
rs.MoveNext
wend
else
Response.Write " <P><Center><font size=""2""><h3>Sorry, but products information for the category you have chosen is not available at this moment. Please check back soon!</H3></font></center>"
catname = "Error"
end if
end sub
%>
<!-- INSIDE BODY TAGS BELOW -->
<!-- Start Profile -->
<div class="span3">
<img src="img/team/profile1.jpg">
<div class="productSelection">
<div class="ProductTitle">
<strong style="font-size:16px;">LOREM IPSUM</strong>
</div>
<h6>LOREMIPSUM</h6>
<h6>LOREM IPSUM</h6>
<%
call openConn()
call productInfo(dbc,catid)
%>
</div>
</div>
<!-- End Profile -->
This is some bad code. The code is closing the form tag twice.
Since you say you only need one button, and since the form tag is either being closed twice or not at all, I think that one of the Response.Write statements needs to be in the other If branch.
'DONT TOUCH THESE BELOW
If rs("stock")="" then
Response.Write "<button class=""btn"" TYPE=""btn"" style=""background-color: #cb0000;color: #fff;"">ADD TO CART</button> </form>"
Else
Response.Write "<button "">ADD TO CART</button></form>"
'DONT TOUCH THESE ABOVE
End If

Assigning Variables from csv file

I have a csv file (sample)
Firm,Code,Server
Adsuar,BZ,RKASP01
Ahlers,AU,RKASP02
Andrews,CW,RKASP02
Armbrecht,AS,RKASP02
Barron,ZZ,RKASP01
Beckman,BI,RKASP02
and am trying to find a way in vbscript to have a single select box on my website that lists the values of column A, and then populate two variables with the contents of column B and C in the same row.
I have what I need to read the csv file and can loop through the file and echo all the contents, however I'm having some trouble finding where to go from here. Any suggestions on where I can start would be appreciated.
The code I have currently is
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("\\rkaspctl01\n$\wwwroot\dev\clients.csv", 1)
do while not (objTextFile.AtEndOfStream)
arrStr = Split(objTextFile.ReadLine, ",")
strFirm = arrStr(0)
strCode = arrStr(1)
strServer = arrStr(2)
Loop
objTextFile.close
Thanks
Patrick Stoddard
Start putting your data in a key/value pair (dictionary) where the key is the value from column A, the value is an array containing the values from column B and C:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("\\rkaspctl01\n$\wwwroot\dev\clients.csv", 1)
Set objFirmDict = CreateObject("Scripting.Dictionary")
do while not (objTextFile.AtEndOfStream)
arrStr = Split(objTextFile.ReadLine, ",")
objFirmDict.Add arrStr(0), array(arrStr(1), arrStr(2))
Loop
objTextFile.close
Now you can populate your listbox with the keys from the dictionary.
Pseudocode:
firmListbox = document.getElementById("firmSelect")
For each firm in objFirmDict.Keys
Set newOption = document.createElement("option")
newOption.text = firm
newOption.value = firm
firmListbox.Add newOption, Nothing
Next
When an option is selected, update the two variables with the correct text.
On you webpage:
<input type="select" id="firmSelect" onchange="vbscript:firmSelectChange me.Value">
The onchange event calls the firmSelectChange sub. This has to retrieve the two variables from the dictionary. Please note: The dictionary must have a global scope for the document.
Pseudocode for this handling sub:
Sub firmSelectChange(value)
dataArr = objFirmDict.Item(value)
code = dataArr(0)
server = dataArr(1)
End Sub
You can use TDC (Tabular Data Control).
<HTML>
<HEAD>
<TITLE>TDC Example</TITLE>
<OBJECT ID="dataTDC" CLASSID="CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<PARAM NAME="TextQualifier" VALUE="">
<PARAM NAME="FieldDelim" VALUE=",">
<PARAM NAME="DataURL" VALUE="data.csv">
<PARAM NAME="UseHeader" VALUE="true">
</OBJECT>
</HEAD>
<BODY>
<TABLE DATASRC="#dataTDC" BORDER="1" CELLSPACING="0">
<THEAD>
<TR>
<TD><B>Firm</B></TD>
<TD><B>Code</B></TD>
<TD><B>Server</B></TD>
</TR>
</THEAD>
<TR>
<TD><SPAN DATAFLD="Firm"></SPAN></TD>
<TD><SPAN DATAFLD="Code"></SPAN></TD>
<TD><SPAN DATAFLD="Server"></SPAN></TD>
</TR>
</TABLE>
</BODY>
</HTML>
Output result:

ASP - Loop while eof or bof - Select random product from idproduct but skip empty ids

I am trying to display a random product image and description from the access database, so i am selecting the highest idproduct then randomising a number between 1 and %highestid%, this is what i have so far....
IF frontpage = 1 then
SQLSTR = "SELECT idproduct AS prodtot FROM products order by idproduct desc"
Set objRS = Server.CreateObject("ADODB.Recordset")
SET objrs = oconn.execute(SQLSTR)
' Check result
Response.Write objRS("prodtot")
' attach
ntop = objRS("prodtot")
Randomize
' Generate random value between 1 and nTop .
nRandom= Int((nTop * Rnd) + 1)
sqlstr = "select * from products where idProduct = " & nRandom
response.Write"<br /><br />" & (sqlstr) & "<br /><br />"
'SET rs = oConn.execute(randomprod)
SET rs = oconn.execute(SQLSTR)
pranproddesc = rs("description")
response.Write(pranproddesc)
pranprodimg = rs("smallImageUrl")
end if
So far so good! But i have a problem, over time products have come and gone and I have alot of gaps in the %idproduct%, ive tried loop while rs.eof but it doesn't seem to do anythimg usefull, if anything at all. Just to clarify I have idproduct 1, 2, 5, 10, 11, 12 etc etc, so when it randomises idproduct3 it all goes up the spout! Can anyone help?
Thank you in advance! :)
Do the following:
IF frontpage = 1 then
Set objRS = Server.CreateObject("ADODB.Recordset")
SET objrs = oconn.execute(SQLSTR)
sqlSTR = "SELECT TOP 1 * FROM products ORDER BY NEWID()"
response.Write"<br /><br />" & (sqlstr) & "<br /><br />"
SET rs = oconn.execute(SQLSTR)
pranproddesc = rs("description")
response.Write(pranproddesc)
pranprodimg = rs("smallImageUrl")
end if
That sql will work in SQL Server:
Look at this page for SQL to return a random row for other databases:
http://www.petefreitag.com/item/466.cfm
Thanks, btw, I learnt something new figuring this out.
Rather than select a random ProductId, select a random row index from the recordset. That way you only have to hit the database once as well :)

Resources