little help on asp - response write - asp-classic

I set a variable :
Dim adoRecordset
and set it as:
Set adoRecordSet = Server.CreateObject("ADODB.RecordSet")
adoRecordset.Open mSQL , adoConnection , adOpenForwardOnly
and I use it into show my data from database
eg. 1. <td align="left"><%=adoRecordset("loc")%></td>
and I would like add a asp code "if" & "else"
but this : 2. Response.Write "<td adoRecordset(loc)></td>"
doesn't work.
How can I make asp code 2. work as 1. ?

My asp classic is rusty, but I think you are looking for something like:
<%
If adoRecordset("loc") <> "" Then
Response.Write(adoRecordset("loc"))
End If
%>
Or with a local var to cache the result:
<%
Dim someLoc
Set someLoc = adoRecordset("loc")
If someLoc <> "" Then
Response.Write("<td>" & someLoc & "</td>")
End If
%>
If you've got large amounts of conditional Html output, then you can switch out of server code again, like so:
<% If something or other Then %>
Some Conditional Html Here
<% Else %>
Else Html here
<% End If %>
<%= is shorthand to emit a value
whereas <% escapes to server side code.

Dim adoRecordset
Set adoRecordSet = Server.CreateObject("ADODB.RecordSet")
adoRecordset.Open mSQL , adoConnection , adOpenForwardOnly
if not adoRecordset.EOF then
do while not adoRecordSet.EOF
if adoRecordset("columnName") = "test value 1" then
response.write("<td>" & adoRecordset("columnName") & "</td>")
else
response.write("<td>I want to do something else here</td>")
end if
adoRecordset.movenext
loop
end if
adoRecordset.close
set adoRecordset = nothing

Related

Removal of <% %> and %><% in Classic ASP when there is nothing between them causes the web page to crash. Why is that?

I am working with Classic ASP and I have a need to make the code simpler. In an effort to do what is similar to what we see here: Auto-populating Select Field via jQuery's Ajax where we use ajax to populate a select filed, we load the contents of a area with by using a separate asp file to load. I assume that the loaded file is free of <% markings. While testing the commands contained in that file I am in the process of removing those marks. Why would removing a %><% mark (where it is just a close followed by an open) throw an error? And why would it be necessary to have something like %>"<% where it is just one character?
The reason why I posted an image of the code block was because the %> and %> symbols were highlighted by color in such a way as to better visualize what was going on.
Here is the code block:
<%
Function FunctionName(name, selection)
%>
<select name = "<%= name%>"><%
Set RTConn = Server.CreateObject("ADODB.Connection")
RTConn.Open("Provider=SQLOLEDB;Password=three4me;Persist Security Info=True;User ID=sa;Initial Catalog=DATABASE;Data Source=SERVER")
Set RT = Server.CreateObject("ADODB.Recordset")
sqlQuery = "SELECT DISTINCT id, Replace(Name, ' ', ' ') AS Name, Num, Address, City, State FROM RedactedTablename WHERE active = 1 OR ID = '" & selection & "' ORDER BY Replace(Name, ' ', ' '), State, City, Num"
RT.Open sqlQuery, RTConn, 3, 3
Do While Not RT.EOF
response.write "<option value=" & RT.Fields("id")
%>" <%
if cstr(RT.Fields("id")) = selection then
response.write " selected "
elseif (selection = "" OR selection = "0") AND trim(RT.Fields("Name")) = "NA" then
response.write " selected "
end if
%>><%=RT.Fields("Name")%><%
if not RT.Fields("Name") = "NA" AND not RT.Fields("Name") = "NA" then
response.write " (" & RT.Fields("City") & ", " & RT.Fields("State") & ") - " & RT.Fields("Num")
end if
%>
response.write"</option>"
<%
RT.MoveNext
Loop
RT.Close
RTConn.Close %>
</select>
<%
End function
%>
The end tag that was removed was paired with a start tag of <%= not <% which has caused the syntax error.
The reason is <%= is a shorthand form of Response.Write and has to be paired with a closing %> tag.
Acceptable:
<%= link_label %>
Invalid syntax:
<%= link_label
Also, there are other issues with the code, for example, #Flakes pointed out in the comments that response.write"</option>" is not located within Classic ASP preprocessor tags (<% and %>).
While this won't cause a syntax error it will cause the line to be interpreted as HTML and will be output to the client as is.

How do I write this IF statement within my ASP page?

I'm trying to display an image on website only if a value in the database is true. I'm using the below code as a template (which is currently working) as my guide, though mine is simpler. Any help would be greatly appreciated.
<% strSQL4 = valid SQL statement
set r4 = d2.execute(strSQL4)
if (r4.EOF = False) and (r4.BOF = False) then
else
r4.moveFirst
while (r4.EOF = False) and (r4.BOF = False) %>
<li><%= r4("Database Field") %></li>
<% r4.movenext
wend
end if %>
That is the code I'm basically emulating, but I'm just trying to display an image if a bool variable is true in a database, per my code below:
<%# ACTLBool = "SELECT ACTL FROM ATTORNEYS WHERE ATTY_ID = " & AttorneyID
if (ACTLBool = True) then %>
<div id="ACTLDiv"><img id="ACTLLogo" src="img/ACTL.jpg" alt="ACTL Logo" /> </div>
<%# else end if %>
I don't need it to do anything if the ACTLBool is false. Any ideas?
assuming conn is your adodb.connection object
Dim rs : set rs = conn.execute("SELECT count(ACTL) as c FROM ATTORNEYS WHERE ATTY_ID = " & CLng(AttorneyId))
If rs("c") > 0 Then
response.write "<div id='ACTLDiv'><img id='ACTLLogo' src='img/ACTL.jpg' alt='ACTL Logo' /> </div>"
End If
Set rs = Nothing

Returning more than 1000 rows in classic asp adodb.recordset

My code in asp classic, doing a mssql database query:
rs.pagesize = 1000 ' this should enable paging
rs.maxrecords = 0 ' 0 = unlimited maxrecords
response.write "hello world 1<br>"
rs.open strSql, conn
response.write "hello world 2<br>"
My output when there are fewer than 1000 rows returned is good. More than 1000 rows and I don't get the "hello world 2".
I thought that setting pagesize sets up paging and thus allows all rows to be returned regardless of how many rows there are. Without setting pagesize, paging is not enable and the limit is 1000 rows. However my page is acting as if pagesize is not working at all.
Please advise.
is it possible you are declaring your oRS.pagesize before you are opening the recordset?
Here is a good example of paging using getrows...
<!--VB ADO Constants file. Needed for the ad... constants we use-->
<!-- #include file="adovbs.inc" -->
<%
' BEGIN USER CONSTANTS
Dim CONN_STRING
Dim CONN_USER
Dim CONN_PASS
' I'm using a DSN-less connection.
' To use a DSN, the format is shown on the next line:
'CONN_STRING = "DSN=DSNName;"
CONN_STRING = "DBQ=" & Server.MapPath("database.mdb") & ";"
CONN_STRING = CONN_STRING & "Driver={Microsoft Access Driver (*.mdb)};"
' This DB is unsecured, o/w you'd need to specify something here
CONN_USER = ""
CONN_PASS = ""
' Our SQL code - overriding values we just set
' Comment out to use Access
CONN_STRING = "Provider=SQLOLEDB;Data Source=10.2.2.133;" _
& "Initial Catalog=samples;Connect Timeout=15;" _
& "Network Library=dbmssocn;"
CONN_USER = "samples"
CONN_PASS = "password"
' END USER CONSTANTS
' BEGIN RUNTIME CODE
' Declare our vars
Dim iPageSize 'How big our pages are
Dim iPageCount 'The number of pages we get back
Dim iPageCurrent 'The page we want to show
Dim strOrderBy 'A fake parameter used to illustrate passing them
Dim strSQL 'SQL command to execute
Dim objPagingConn 'The ADODB connection object
Dim objPagingRS 'The ADODB recordset object
Dim iRecordsShown 'Loop controller for displaying just iPageSize records
Dim I 'Standard looping var
' Get parameters
iPageSize = 10 ' You could easily allow users to change this
' Retrieve page to show or default to 1
If Request.QueryString("page") = "" Then
iPageCurrent = 1
Else
iPageCurrent = CInt(Request.QueryString("page"))
End If
' If you're doing this script with a search or something
' you'll need to pass the sql from page to page. I'm just
' paging through the entire table so I just hard coded it.
' What you show is irrelevant to the point of the sample.
'strSQL = "SELECT * FROM sample ORDER BY id;"
' Sept 30, 1999: Code Change
' Based on the non stop questions about how to pass parameters
' from page to page, I'm implementing it so I can stop answering
' the question of how to do it. I personally think this should
' be done based on the specific situation and is clearer if done
' in the same method on all pages, but it's really up to you.
' I'm going to be passing the ORDER BY parameter for illustration.
' This is where you read in parameters you'll need for your query.
' Read in order or default to id
'If Request.QueryString("order") = "" Then
' strOrderBy = "id"
'Else
' strOrderBy = Replace(Request.QueryString("order"), "'", "''")
'End If
' Make sure the input is one of our fields.
strOrderBy = LCase(Request.QueryString("order"))
Select Case strOrderBy
Case "last_name", "first_name", "sales"
' A little pointless, but...
strOrderBy = strOrderBy
Case Else
strOrderBy = "id"
End Select
' Build our SQL String using the parameters we just got.
strSQL = "SELECT * FROM sample ORDER BY " & strOrderBy & ";"
' Some lines I used while writing to debug... uh "test", yeah that's it!
' Left them FYI.
'strSQL = "SELECT * FROM sample WHERE id=1234 ORDER BY id;"
'strSQL = "SELECT * FROM sample;"
'Response.Write "SQL Query: " & strSQL & "<BR>" & vbCrLf
' Now we finally get to the DB work...
' Create and open our connection
Set objPagingConn = Server.CreateObject("ADODB.Connection")
objPagingConn.Open CONN_STRING, CONN_USER, CONN_PASS
' Create recordset and set the page size
Set objPagingRS = Server.CreateObject("ADODB.Recordset")
objPagingRS.PageSize = iPageSize
' You can change other settings as with any RS
'objPagingRS.CursorLocation = adUseClient
objPagingRS.CacheSize = iPageSize
' Open RS
objPagingRS.Open strSQL, objPagingConn, adOpenStatic, adLockReadOnly, adCmdText
' Get the count of the pages using the given page size
iPageCount = objPagingRS.PageCount
' If the request page falls outside the acceptable range,
' give them the closest match (1 or max)
If iPageCurrent > iPageCount Then iPageCurrent = iPageCount
If iPageCurrent < 1 Then iPageCurrent = 1
' Check page count to prevent bombing when zero results are returned!
If iPageCount = 0 Then
Response.Write "No records found!"
Else
' Move to the selected page
objPagingRS.AbsolutePage = iPageCurrent
' Start output with a page x of n line
%>
<p>
<font size="+1">Page <strong><%= iPageCurrent %></strong>
of <strong><%= iPageCount %></strong></font>
</p>
<%
' Spacing
Response.Write vbCrLf
' Continue with a title row in our table
Response.Write "<table border=""1"">" & vbCrLf
' Show field names in the top row
Response.Write vbTab & "<tr>" & vbCrLf
For I = 0 To objPagingRS.Fields.Count - 1
Response.Write vbTab & vbTab & "<th>"
Response.Write objPagingRS.Fields(I).Name
Response.Write "</th>" & vbCrLf
Next 'I
Response.Write vbTab & "</tr>" & vbCrLf
' Loop through our records and ouput 1 row per record
iRecordsShown = 0
Do While iRecordsShown < iPageSize And Not objPagingRS.EOF
Response.Write vbTab & "<tr>" & vbCrLf
For I = 0 To objPagingRS.Fields.Count - 1
Response.Write vbTab & vbTab & "<td>"
Response.Write objPagingRS.Fields(I)
Response.Write "</td>" & vbCrLf
Next 'I
Response.Write vbTab & "</tr>" & vbCrLf
' Increment the number of records we've shown
iRecordsShown = iRecordsShown + 1
' Can't forget to move to the next record!
objPagingRS.MoveNext
Loop
' All done - close table
Response.Write "</table>" & vbCrLf
End If
' Close DB objects and free variables
objPagingRS.Close
Set objPagingRS = Nothing
objPagingConn.Close
Set objPagingConn = Nothing
' Show "previous" and "next" page links which pass the page to view
' and any parameters needed to rebuild the query. You could just as
' easily use a form but you'll need to change the lines that read
' the info back in at the top of the script.
If iPageCurrent > 1 Then
%>
[<< Prev]
<%
End If
' You can also show page numbers:
For I = 1 To iPageCount
If I = iPageCurrent Then
%>
<%= I %>
<%
Else
%>
<%= I %>
<%
End If
Next 'I
If iPageCurrent < iPageCount Then
%>
[Next >>]
<%
End If
' END RUNTIME CODE
%>
Try changing your rs.open line to:
rs.Open strSQL, Conn, 3, 1, &H0001
Here's the breakdown of the function call and parameters:
recordsetobject.Open Source, ActiveConnection, CursorType, LockType, Options
3 - adOpenStatic
1 - adLockReadOnly
&H0001 - adCmdText
I pull this from some old code of mine. I don't remember why this combination of parameters is necessary but it's what is necessary to implement paging.
Unlimited records sounds great but I would set a limit even if it's quite hi.
If you are not getting the "Hello World 2" output, is there an error? That would be helpful as well.
paging is for just that, paging.
your code here is not enough to accomplish that but regardless of the code, why are you trying to return a 1000 rows of data ????
nobody's going to read a 1000 rows of data and it will likely be very slow performance.
Using the following code, I returned 4000+ rows from a sql server table in classic ASP. It's not using the same method, but it doesn't suffer the limitations either.
strconnect = "DRIVER={SQL Server};SERVER=****;DATABASE=****;UID=****;PWD=****"
set conn=server.createobject("adodb.connection")
conn.open strconnect
set rs = conn.execute("select firstname from users")
if not rs.eof then
f_Array = rs.getrows
end if
rs.close
set rs = nothing
conn.close
set conn = nothing
for x = 0 to ubound(f_Array, 2)
response.write (x+1) & ". " & f_Array(0,x) & "<br />"
next

Populate Dropdown from SQL in Classic ASP

I am trying to force users to only select certain values when adding a record. So naturally I am using a dropdown, but I'd like the options to be populated by a specific field in the database. I figured I'd do a Do/Loop but I am apparently doing something wrong.
Dim dstrSQL
Dim drs
dstrSQL = "SELECT EventID FROM Events"
set conn2 = CreateObject("ADODB.Connection")
conn2.open CONN_STRING
set drs = conn2.execute(dstrSQL)
conn2.close: set conn2 = nothing
Do
Response.Write "<option value=" & drs.Fields(0) & " >" & drs.Fields(0) & "</option>"
drs.MoveNext
Loop
It's been a long time. Something like this:
conn2.open CONN_STRING
set drs = conn2.execute(dstrSQL)
do while not drs.eof %>
<option value="<%= drs.Fields(0) %>" ><%= drs.Fields(0) %></option>
<% drs.MoveNext
Loop
conn2.close
set conn2 = nothing %>

ASP How do I insert a username into a table?

I'm struggling with my code below, I'm reading the logged on users username and trying to insert their name into a SQL table called licenses, the table contains 2 columns 1 contains license numbers the other is all nulls at the moment but a username should be inserted along side one when this page loads. Currently the page just loops constantly and nothing is inserted into the table. The user inside connection1.asp does have read/write access to the database.
Any ideas? Thanks
<%#LANGUAGE="VBSCRIPT" LCID=1033%>
<%
aName = Split(Request.ServerVariables("LOGON_USER"), "\")
user = aName(UBound(aName))
user = UCase(user)
Erase aName
%>
<!--#include file="Connections/connection1.asp" -->
<%
Dim Recordset1
Dim Recordset1_numRows
Set Recordset1 = Server.CreateObject("ADODB.Recordset")
Recordset1.ActiveConnection = MM_connection1_STRING
Recordset1.Source = "SELECT * FROM Licenses2 WHERE userid = '" & user & "';"
Recordset1.Open()
%>
<HTML><HEAD></HEAD>
<BODY leftmargin="5" onLoad="setTimeout('reloadFunction()',500000)">
<% Do While NOT Recordset1.EOF %>
<% strUserName =(Recordset1.Fields.Item("userid").Value)%>
<% response.write strUserName %>'s Serial Number:
<% strSerial =(Recordset1.Fields.Item("serial").Value)%>
<% response.write strSerial %>
<% Recordset1.movenext %>
<% loop %>
<%
If strUserName = user then
'record found do nothing
'response.write "user found"
else
adoCon.Execute = "SET ROWCOUNT 1; UPDATE Licenses2 SET userid = '" & user & "' WHERE userid = 'NULL';"
Response.AddHeader "Refresh", "3"
End if
%>
</BODY>
</HTML>
<%
Recordset1.Close()
Set Recordset1 = Nothing
Set Recordset2 = Nothing
%>
If the user is NOT found, should you be doing an INSERT instead of UPDATE?
If the UPDATE is correct, change the last NULL ... remove the quotes. Right now you are comparing a STRING value of 'NULL' instead of the value NULL and it should be IS NULL
SET ROWCOUNT 1; UPDATE Licenses2 SET userid = '" & user & "' WHERE userid IS NULL;
Also, see if you can comment out the <BODY ... > tag and create a new one without the RELOADFUNCTION and see if that makes a difference.
Lastly, read up on SQL Injection because your code is prone to Injection attacks. Search on StackOverflow.com for SQL Injection and you will find plenty of explanations, examples and cures.
Check if LOGON_USER is actually returning any data. If you have IIS security set to 'Anonymous' access then this will not be populated with anything.
Your code would also be potentially prone to SQL injection attacks.

Resources