Insert looped variable to one table column - asp-classic

I have Checkbox form and I am trying to save my loops values into a variable.
This is how I am looping:
For i = 1 to Request.Form("packages").count
Set packnamn = ObjConn.Execute ("Select * from services_package where id='"&
Request.Form("packages")(i) &"'")
panamn = packnamn("name") & "-"
Response.write panamn
Next
This will output
Greece-English-Spanish-
Now im trying to save the whole output in my MySQL. But i'm only getting the last value of the loop (Spanish-), This is my insert code.
Dim sql1
sql1= "insert into tariff_plan(package)"
sql1=sql1 & " VALUES "
sql1=sql1 & "('" & panamn &"')"
on error resume next
ObjConn.Execute sql1,recaffected
if err<>0 then
Response.Write(err.description)
else
response.write "Saved"
End if

You have to add the values to a variable where you are doing the response.write and do the insert after the loop.
panamn = ""
For i = 1 to Request.Form("packages").count
Set packnamn = ObjConn.Execute ("Select * from services_package where id='"&
Request.Form("packages")(i) &"'")
panamn = panamn & packnamn("name") & "-"
Next
Response.write panamn
'Do the insert here

Related

How to reuse an array in asp.net vb

I'm having to build a table of web pages and languages, i.e. page 1: en it de in a schema where there could be up to 14 languages. The page contents are held in a database. So to build the table I'm doing the following:
Dim rowArrayList As New ArrayList
Dim thisRow(languageNum) As String 'languageNum equates to number of columns -1
Database access then:
'# Create row array of cell arrays
If pageName <> lastPageName Then
lastPageName = pageName
If j >= languageNum Then
rowArrayList.Add(thisRow)
Array.Clear(thisRow, 0, thisRow.Length)
j = 0
End If
thisRow(0) = "<td class=""pageName"">" & pageName & "</td>"
End If
'# Iterate each cell in the row
For i As Integer = 1 To languageNum - 1
If thisRow(i) = "" Then
If transReady = False And active = False Then
thisRow(i) = "<td class=""trans"">" & langISO & "</td>"
ElseIf transReady = True And active = False Then
thisRow(i) = "<td class=""notActive"">" & langISO & "</td>"
ElseIf transReady = True And active = True And i = thisLangID Then
thisRow(i) = "<td class=""active"">" & langISO & "</td>"
End If
End If
j = j + 1
Next
The build the table:
'# Build output table
For Each row As String() In rowArrayList
tableBody.Text += "<tr>"
For Each cell As String In row
If cell = "" Then
tableBody.Text += "<td class=""notTrans""> </td>"
Else
tableBody.Text += cell
End If
Next
tableBody.Text += "</tr>"
Next
The table displays beautifully BUT every row contains the data for what should be the last row. How can it be fixed it so each thisRow is unique in the the rowArrayList? At the moment, every time thisRow is added to rowArrayList, every rowArrayList index is overwritten, not just the one being added.
For the quick fix, instead of this:
Array.Clear(thisRow, 0, thisRow.Length)
Do this:
thisRow = New String(languageNum) {}
or this:
ReDim thisRow(languageNum)
However, I suspect there are some simple design choices you could change that would drastically change this code for the better.

Having a BOF or EOF error, after call recordCount

I have to call recordCount function to get the count of recordset.
But once I call recordCount function, the recordset is out of control.
...
Dim objRootDSE, strDNSDomain, adoCommand, adoConnection
Set adoCommand = CreateObject("ADODB.Command")
'Set adoRecordset = adoCommand.Execute
Set adoRecordset = Server.CreateObject ("ADODB.Recordset")
adoRecordset.cursorType = 3
adoRecordset.CursorLocation = adUseClient
adoRecordset = adoCommand.Execute
...
totalcnt = adoRecordset.recordCount
If totalcnt > 0 Then
...
Do until adoRecordset.EOF
' Retrieve values... But it fails because it seems adoRecordset is in EOF
...
So I use movefirst and try to retrieve values.
If adoRecordset.recordCount > 0 Then
adoRecordset.movefirst
...
But it occurs an error(below is translated by google)
ADODB.Recordset 오류 '800a0bcd'
BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
If I didn't call recordCount, there's no problem. But I should know the count of record.
The whole code is :
<%
'On Error Resume next
Dim objRootDSE, strDNSDomain, adoCommand, adoConnection
Dim strBase, strFilter, strAttributes, strQuery, adoRecordset
Dim strDN, strUser, strPassword, objNS, strServer
Dim name,company,physicalDeliveryOfficeName
Const ADS_SECURE_AUTHENTICATION = 1
Const ADS_SERVER_BIND = 0
' Specify a server (Domain Controller).
strServer = "my_ad_server_domain"
' Specify or prompt for credentials.
strUser = "my_account"
strPassword = "my_passwrd"
' Determine DNS domain name. Use server binding and alternate
' credentials. The value of strDNSDomain can also be hard coded.
Set objNS = GetObject("LDAP:")
Set objRootDSE = objNS.OpenDSObject("LDAP://" & strServer & "/RootDSE", _
strUser, strPassword, _
ADS_SERVER_BIND Or ADS_SECURE_AUTHENTICATION)
strDNSDomain = objRootDSE.Get("defaultNamingContext")
' Use ADO to search Active Directory.
' Use alternate credentials.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Properties("User ID") = strUser
adoConnection.Properties("Password") = strPassword
adoConnection.Properties("Encrypt Password") = True
adoConnection.Properties("ADSI Flag") = ADS_SERVER_BIND _
Or ADS_SECURE_AUTHENTICATION
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
' Search entire domain. Use server binding.
strBase = "<LDAP://" & strServer & "/" & strDNSDomain & ">"
' Search for all users.
strFilter = "(&(objectCategory=user)(ExADObjectStatus=10)(samaccountname=*"&"my_search_value"&"*))"
' Comma delimited list of attribute values to retrieve.
strAttributes = "name,company,physicalDeliveryOfficeName"
' Construct the LDAP query.
strQuery = strBase & ";" & strFilter & ";" _
& strAttributes & ";subtree"
' Run the query.
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 60
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute
if not adoRecordset.EOF then
totalcnt = adoRecordset.recordCount
If totalcnt > 0 Then
Response.write 111
Do until adoRecordset.EOF
name = adoRecordset.Fields("name").Value
company = adoRecordset.Fields("company").Value
physicalDeliveryOfficeName = adoRecordset.Fields("physicalDeliveryOfficeName").Value
Response.Write name & "<br/>"
Response.Write company & "<br/>"
Response.Write physicalDeliveryOfficeName
adoRecordset.MoveNext
Loop
end if
end if
' Clean up.
adoRecordset.Close
adoConnection.Close
%>
It shows only one result of record.
You can try to face the problem from a different angle. Instead of trying to fix the internal recordCount property (which you can't) simply count the records yourself:
totalcnt = 0
Do until adoRecordset.EOF
totalcnt = totalcnt + 1
adoRecordset.MoveNext
Loop
If totalcnt>0 Then
adoRecordset.MoveFirst
Do until adoRecordset.EOF
name = adoRecordset.Fields("name").Value
'...
adoRecordset.MoveNext
Loop
End If
Update: Looks like in that specific case, the MoveFirst just fails, maybe because it's LDAP and not ordinary query from a database. To bust this once and for all, you can populate your own collection when iterating the records then use that collection as much as you like:
Dim oData, oField, tempArray
Set oData = Server.CreateObject("Scripting.Dictionary")
totalcnt = 0
For Each oField In adoRecordset.Fields
oData.Add oField.Name, Array()
Next
Do until adoRecordset.EOF
For Each oField In adoRecordset.Fields
tempArray = oData(oField.Name)
ReDim Preserve tempArray(UBound(tempArray) + 1)
tempArray(UBound(tempArray)) = oField.Value
oData(oField.Name) = tempArray
Next
totalcnt = totalcnt + 1
adoRecordset.MoveNext
Loop
adoRecordset.Close
Dim x
If totalcnt>0 Then
Response.Write("found total of " & totalcnt & " records<br />")
For x=0 To totalcnt-1
name = oData("name")(x)
company = oData("company")(x)
physicalDeliveryOfficeName = oData("physicalDeliveryOfficeName")(x)
Response.Write name & "<br/>"
Response.Write company & "<br/>"
Response.Write physicalDeliveryOfficeName
Next
End If
As the error indicates, the recordCount fails if you have no records in the recordset.
You can test for this before your code block. Try this:
if not adoRecordset.EOF then
totalcnt = adoRecordset.recordCount
If totalcnt > 0 Then
...
Do while not adoRecordset.EOF
...
Loop
end if
end if
edit: Corrected the loop to test for not adoRecordset.eof

Read the values stored in text file separated by comma and display them one by one in classic asp

I have a text file having three fields category name, image name and link or URL. The three fields are stored in the text file separated by comma. I want to read the textfile values and display them one by one that is in a column format. So all the category names will be displayed in one column, image name in one column and link in one column.
I have read the text file and i get all the contents in text file in a variable. The content that i get in variable is as follows:
glass,glassbowlcategory.jpg,www.google.com glass,glassbowlcategory.jpg,www.google.com glass bowl,images1.jpg,http://www.fitnessfirstusa.com/catalog.asp?Brand=LG%20Sciences
In the above string first one is category name, second is image name and third is link.
I have used the folllowing code to read text file.
Sub BuildFileList(strFolder)
Dim strFileName1
Dim strSearchText
Dim objFSO, objTextFile
Dim strReadLineText
Dim intLineNumber,strNewContents
Dim strLineNumbers
Dim objFile
' Name of text file to search:
'
'strFileName = "readme.txt"
strFileName1 = "saveimagename.txt"
Const ForReading = 1
Const ForWriting = 2
'' Create an instance of the the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName1))
intLineNumber = 0
'
strLineNumbers = ""
Do While Not objTextFile.AtEndOfStream
intLineNumber = intLineNumber + 1
strReadLineText = objTextFile.ReadLine
' response.Write(strReadLineText)
strNewContents = strNewContents & strReadLineText & vbCrLf
response.Write(strNewContents)
'
Loop
end sub
Please advise how can i split the contents that i get in the variable and display them
For tabular data
Const ForReading = 1
Const ForWriting = 2
Dim objTextFile
Dim intLineNumber, strNewContents, strReadLineText
dim data, columns
strFileName1 = "saveimagename.txt"
Set objTextFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(Server.MapPath(strFileName1))
intLineNumber = 0
strLineNumbers = ""
data = split(objTextFile.readall(), vbcrlf)
for intLineNumber = 0 to ubound(data)
columns = split(data(intLineNumber), ",", 3)
if (ubound(columns) = 2) then
strNewContents = strNewContents & "<tr><td>" & columns(0) & "</td><td>" & columns(1) & "</td><td>" & columns(2) & "</td></tr>" & vbcrlf
end if
next
response.write "<table>" & strNewContents & "</table>"
perhaps you could use Microsoft ActiveX Database Objects (ADO) for that?
here are some links:
Much ADO about Text Files
Microsoft ODBC Desktop Database Drivers
and some sample code:
'http://msdn.microsoft.com/en-us/library/ms974559.aspx
dim conn : set conn = server.createObject("ADODB.Connection")
dim rs : set rs = server.createObject("adodb.recordset")
dim sql
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
importPath & ";" &_
"Extended Properties=""text;HDR=" & HDR & ";FMT=Delimited"""
sql = "SELECT * FROM " & myImportFile
rs.open sql, conn, adOpenStatic, adLockOptimistic, adCmdText

Classic ASP sub procedure call in Response.Write

I have a classic ASP question.
Attempting to do this: the recordset is a simple list of years from 1995 to 2020; and i am trying to make 2010(current year) the default selection in the drop down.
issue: I trying to call a Sub proc in "Response.Write", but it keeps giving me this error:
"Error '800a000d' Type mismatch: 'selectyear' "
Below is the code, the Attempt 1 works with out any problem. But when i move that "if" logic to a sub procedure and call it in the Request.Write, it gives me the error.
Can any one please explain why Attempt1 works and Attempt2 wouldnt.
' Attempt 1:
rsYEAR.Open qYEAR, objconn, 0, 1
response.Write "<tr><td>Year:</td> <td> <select name='theyear' style=""WIDTH: 67px"">"
dim selyr
while not rsYEAR.EOF
if CINT(rsYEAR.fields("year")) = year(now) then
selyr = "selected"
else selyr = ""
end if
Response.Write"<option value='" & rsYEAR.fields("year") & "' "& selyr &" >" & cstr(rsYEAR.Fields("year"))
rsYEAR.MoveNext
wend
response.Write "</select></td></tr>"
rsYEAR.Close
' Attempt 2:
rsYEAR.Open qYEAR, objconn, 0, 1
response.Write "<tr><td>Year:</td> <td> <select name='theyear' style=""WIDTH: 67px"">"
dim selyr2
while not rsYEAR.EOF
Response.Write "<option value='" & rsYEAR.fields("year") & "' " & cstr(selectyear(cint(rsYEAR.fields("year")))) &" >" & cstr(rsYEAR.Fields("year"))
rsYEAR.MoveNext
wend
response.Write "</select></td></tr>"
'close and clean up
rsYEAR.Close
set rsYEAR = nothing
I would greatly appreciate your response.
thank you,
Shiva
I am guessing that cint(rsYEAR.fields("year")) is throwing the error because there is data that cannot be converted to int. I would expect that to happen in both cases though.
You shouldn't need the cstr in cstr(selectyear(cint(rsYEAR.fields("year")))) in the second attempt, as I assume selectyear is already returning a string. Can you show the code for selectyear?
(How has this sat for so long without a correct answer?)
A Sub does not have a value, so you can't Response.Write it. You need to either use a function, or put the Sub call on its own line.
rsYEAR.Open qYEAR, objconn, 0, 1
response.Write "<tr><td>Year:</td><td><select name='theyear' style=""width: 67px"">"
dim y
while not rsYEAR.EOF
y = rsYEAR.fields("year")
Response.Write "<option value='" & y & "'" & IsCurr(y) & ">" & y & "</option>"
rsYEAR.MoveNext
wend
response.Write "</select></td></tr>"
rsYEAR.Close
Function IsCurr(yr)
if Cstr(yr) = Cstr(year(now)) then
IsCurr = " selected"
else
IsCurr = ""
end if
End Function
Using a sub instead of a function, this would become
rsYEAR.Open qYEAR, objconn, 0, 1
response.Write "<tr><td>Year:</td><td><select name='theyear' style=""width: 67px"">"
dim y
while not rsYEAR.EOF
y = rsYEAR.fields("year")
Response.Write "<option value='" & y & "'"
IsCurr y
Response.Write ">" & y & "</option>"
rsYEAR.MoveNext
wend
response.Write "</select></td></tr>"
rsYEAR.Close
Sub IsCurr(yr)
if Cstr(yr) = Cstr(year(now)) then
Response.Write " selected"
end if
End Sub

putting values from database into a drop down list

my tool is in asp. i am using this code for a query in sql
dim req_id
req_id=Request.Form("Req_id")
if req_id<>"" then
Set conn=server.CreateObject("adodb.connection")
conn.Open session("Psrconnect")
Set rs=CreateObject("Adodb.Recordset")
rs.Open "select * from passwords where REQ_ID='"&req_id&"'", conn
i want to put the results of this query into a drop down list. how do i do it? any help is very much appreciated.
Slightly edited code from my working pages :
function HtmlFormOption( byval psReturnValue, byval psDisplayValue ,byval psCurrentDefault)
dim x
if IsNull(psCurrentDefault) then psCurrentDefault = ""
if IsNull(psReturnValue) then psReturnValue = ""
if lCase( cStr(psReturnValue) ) = lCase( cStr(psCurrentDefault)) then
x = "selected "
else
x = ""
end if
HtmlFormOption = "<option " & x & "value='" & psReturnValue & "'>" & psDisplayValue & "</option>"
end function
dim Result, sCode, sWaarde
Result = "<select name='NameCombobox' size='1'>" & vbCrlf
while not objRecLookup.Eof
sCode = objRecLookup.Fields(0) ' first field in result set
sWaarde = objRecLookup.Fields(1) ' second field in result set
if not IsNull(sCode) and not IsNull(sWaarde) then
Result = Result & HtmlFormOption( sCode, sWaarde , psCurrentDft )
end if
objRecLookup.MoveNext
wend
objRecLookup.Close
Result = Result & "</select>" & vbCrlf
And than Response.Write(Result)
Here's a simple solution:
<%
Dim objCommand, objRS
Set objCommand = Server.CreateObject("ADODB.Command")
with objCommand
.ActiveConnection = objConn
.CommandType = adCmdText
.CommandText = "SELECT * FROM PASSWORDS WHERE REQ_ID= '" & req_id & "'"
Set objRS = .Execute
end with
%><select name="selectbox"><%
While NOT objRS.EOF
%><option value="<%=objRS("COLUMN_NAME")%>"><%=objRS("COLUMN_NAME")%></option><%
objRS.MoveNext
Wend
%></select><%
objRS.Close
Set objRS = Nothing
Set objCommand = Nothing
%>

Resources