Link to home
Start Free TrialLog in
Avatar of higgsy
higgsy

asked on

Check if variable has been declared in ASP

Hi,

Im writing a script and i want to check whether a variable has been declared or not. My database connection name is objConn, and so i want to check whether that variable has been declared, if it hasnt the user is on a page that has no database driven content and so i dont want to query the DB...

I use IsObject(objConn) to check whether the variable is an object but because i have option explicit on every page that returns an error...

I could turn on On Error Resume Next before the IsObject statement but i dont like to do this because i will never know if theres an error.

Any ideas or solutions anyone....

Thanks in advance
Al Higgs

Avatar of justjuice
justjuice

objToFind = "myobj"
objfound = false

For Each Item in Application.Contents
   If Item = objToFind Then
      objFound = true
      Exit For
   End If
Next

response.write("Object found?:" & objFound)
Actually, why couldn't you just dim "objConn" globally and make it equal nothing - setting as an object when required? IsOBject wouldnt fail then.
Avatar of Ryan Chong
Try define a function like below to check to see if the connection establish or not:

<%
      
      function isDBConnectionOk(dbpath)
      on error resume next
      set conn=server.CreateObject("adodb.connection")
      conn.Open "Provider=MICROSOFT.JET.OLEDB.4.0;DATA SOURCE="+dbpath
      if conn.state = 1 then
            isDBConnectionOk = true
      else
            isDBConnectionOk = false
      end if
      conn.close
      set conn = nothing
      end function
%>

then

<%

 if isDBConnectionOk("E:\sites\domain\databases\domain.mdb") then
       'database connection ok
else
       'database connection failed
end if

%>
ASKER CERTIFIED SOLUTION
Avatar of justjuice
justjuice

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
higgsy,
You can use TypeName() too to detect what type of the variables.
Eg:
<%
 Dim x
 x=request("strName")
 Response.Write("VarType : " & TypeName(x))
%>

But, i believe after you put "Option Explicit" should alert for any undeclare variables. Then, you can know/fix which variables is still not declare.

Regards
x_com
As you are using Option Explicit, you have to declare the variable objConn if you want to check it's status.

I would rather put a constant in the include file that determines if the connection is opened:

Const blnHasDatabase=True

Then in the files without database connection, I would put:

Const blnHasDatabase=False

Then you simply check the constant for the status:

If blnHasDatabase Then
   ... do the query
End If