Response.Write in ASP

Changes are if you are using ASP you will sometime want to write in something into a page without going back into HTML. You can always open an IF then close the ASP script write in your HTML then open the ASP script up again and END IF. However this is not always practical.

When it’s needed

Some WYSIWYG editors will display little ASP icons where ASP scripts are and if you are using one page to house several pages of content then you will want it all to be inside the ASP script so that it doesn’t mess up and stretch the layout of your page.

However if you are opening and closing ASP scripts with HTML in between, all the HTML will display in between all these scripts and will be fully visible on your page rather than being contained in the little ASP script icon.

Another instance would be when you want your HTML content to be in a variable. Say if you wanted to use the same block of HTML script in two places or repeatedly say for a newsletter script then it would be easy if all the HTML was in a variable you could just include anywhere in your ASP script.

Being ASP ready

Most HTML tags will go in the basic format for Response Write in ASP fine as there are no limitations as its al contained within markers to show what is ASP script and what is the content you are setting as a variable. For example:

Response.Write("all the code goes here and its all contained in this area nicely")

The problem is that often in HTML, the quote mark is used. But using one of these ” in a response write ASP command will close the Response Write area and code will be left out and start causing all sorts of errors. For example:

Response.Write("<img src="somepath_is_outside_the_quotes"")

Quoting the problem

How do you contain these problems then? By removing or even adding quotes. The first option is to simply remove all the quotes or as many as you can. This means that it isn’t formatted correctly and W3C won’t be happy with you but they never are anyway ;). It will still work in the user’s browser at any rate.

<img src=somefile.gif width=100 height=200 border=0 />

This code appears fine, and it would display fine. This can then be put between the quotes in a Response Write tag in ASP. Problems do not end there though – what happens if your need spaces in a variable. There you couldn’t use the above tactic.

Spaces and doubles

Take a look at the following code. There may be better examples but this one works fine. Its an image with an ALT tag with some keywords in it.

<img src=somefile.gif border=0 alt="some keywords go here" />

There is a problem. The ALT tag has spaces in, so after some, the browser may think that everything beyond there is something else. And with good reason as we could replace keywords go here with width=50 and we wouldn’t want that to be part of the ALT tag.

The solution it to use double quotes.

<img src=somefile.gif border=0 alt=""some keywords go here"" />

This keeps the ASP code correct and adds a quote into the HTML when it is sent to the browser. It’s a bit longer and more code that usual but you can easily change all the ” to “” with a quick find and replace.

Using Request in ASP

The request function, suprising requests a value. This could be a query string, form variable, or some other value. For example if you were at the following URL.

http://www.somepage.com/home.asp?ID=23

And you had a script as such.

Request.QueryString("ID")

The call would return the value 23.

An example of where this can be used is on the M World News channel. The news is stored dynamically in a databasde so when you click on a link to the full story from the news homepage you are taken to a dynamic page which selects the story based on the ID of the story you want passed to the page as a url variable. For example the link could be:

http://www.mworld.us/news/story.asp?ID=52

Examples of use:

Request.QueryString("SomeURLVariable")
Request.Form("SomeFormElement")
Request.Cookies("SomeCookie")

Hello World in ASP

This is how to do a basic Hello, World! in ASP.

<html>
<head>
<title>Hello World in ASP</title>
</head>
<body>

<%
Response.Write("Hello, World!")
%>

</body>
</html>

There are two parts. The first is the Response, this tells the server that it needs to do something – to send something out as it were. The second part, in this case Write, is what it has to do.

ASP basics

ASP code is added like scripts to HTML. You open an ASP script using the tag.

<%

You close it using the reverse.

%>

Therefore in a HTML page it would look like the following.

<html>
<head>
<title>Example script</title>
</head>
<body>

<%
' here is some ASP script
%>

</body>
</head>

Notice the use of a comment in the script.

<%
' This is an ASP comment
' Here is another
%>

Query strings not detected in ASP

Problem: You are requesting QueryString’s in ASP but nothing happens and the value seems to be empty.

Cause: You cannot use default documents when requesting QueryString’s. For example:

http://www.somefile.com/search/index.asp?q=hello

Would pick up that the query string “q” is set to “hello.” However:

http://www.somefile.com/search/?q=hello

Would not pick up anything despite index.asp being loaded as the default document.

Fix: Enter the full url instead of skipping out the file name.

A simple hit counter in ASP

This tutorial will show you how to build a simple hit counter. It does not use any SQL or databases; it stores the hits in a text file.

Allou need to create for this script is your ASP file and a text file. In the text file, simply enter the number 0 and save it in the same directory as count.txt. Take a look at the basic source code.

<%@ Language="VBScript" %>
<% Response.Expires= -1
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Pragma", "no-cache" %>
<%
if Session("ct") = "" then
fp = Server.MapPath("db\count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)
ct = ct + 1
Session("ct") = ct
a.close
Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close
Set a = Nothing
Set fs = Nothing
else
ct = Clng(Session("ct"))
end if 
%>

Now lets break it down into three sections.

<%@ Language="VBScript" %>

This just states that the page is a VB script page.

<% Response.Expires= -1
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Pragma", "no-cache" %>

This section stops the user refreshing the page to clock up hits.

<%
if Session("ct") = "" then
fp = Server.MapPath("count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)
ct = ct + 1
Session("ct") = ct
a.close
Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close
Set a = Nothing
Set fs = Nothing
else
ct = Clng(Session("ct"))
end if 
%>

This is the main section which adds the hits.

fp = Server.MapPath("count.txt")

This tells the server where to find the file. You can modify the file location by changing count.txt. So for instance if you wanted to to be called hitcounter.txt and in the directory db you would use:

fp = Server.MapPath("db\hitcounter.txt")

All you have to do is alter the file path in the quote marks.

Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)

This section opens the file using FileSystemObject and reads the first line. It then sets the variable ct to the amount of hits it has already had.

ct = ct + 1

This line adds one hit to the total number of visitors.

Session("ct") = ct
a.close

This part saves a session variable as the new click through with the new amount of visitors and closes the text file.

Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close

This code creates a new text file over the old one and adds in the new amount of visitors to it. Then it closes the text file.

Now you have a working hit counter. All you need to do is add the hit counter into your page:

You are a visitor number <%=ct%>!

This would display the amount of visitors. Now to save confusion, here is the full source code for the page:

<%@ Language="VBScript" %>
<% Response.Expires= -1
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Pragma", "no-cache" %>
<%
if Session("ct") = "" then
fp = Server.MapPath("db\count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)
ct = ct + 1
Session("ct") = ct
a.close
Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close
Set a = Nothing
Set fs = Nothing
else
ct = Clng(Session("ct"))
end if 
%>
<html>
<body>
You are a visitor number <%=ct%>!
</body>
</html>

Using Server.MapPath in ASP

Server.MapPath is used to create a file path from a virtual path.

Here’s a typical DNS-less database connection:

Connection = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\wwwroot\users\someaddress\db\data.mdb"

This isn’t much good though if you don’t know the full file path and if you are using a web host the chances are that you won’t know it. So you can use Server.MapPath instead.

Lets say that database is on the internet at the following address. Not that it is a good idea to have your database web accessible of course.

http://www.someaddress.com/db/data.mdb

Instead of having to use the file path as the top you could use a virtual path:

Connection = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" + Server.MapPath("/db/data.mdb")

This would get the server to “map” a file path to the database from the virtual path you give it. Notice that after DBQ= the tag (“) is closed as you don’t want the server to think + Sever.Map… is part of the file path.

ASP Request function

The request function, surprisingly, requests a value. This could be a URL variable, form variable, or some other value. For example if you were at the url.

http://www.somepage.com/home.asp?ID=23

You would use the following code in your script.

Request.QueryString("ID")

The line would then return the value 23.

An example of where this can be used is on the M World News channel. The news is stored dynamically in a database so when you click on a link to the full story from the news homepage you are taken to a dynamic page which selects the story based on the ID of the story you want passed to the page as a url variable. For example the link could be as follows.

http://www.mworld.us/news/story.asp?ID=52

Examples of use

Request.QueryString("SomeURLVariable")
Request.Form("SomeFormElement")
Request.Cookies("SomeCookie")

Accessing MySQL with ASP

Being an active server page coder by nature, all my sites are in ASP. So eventually I hit a problem – two sites want to use the same Access database but they are on different hosts. Therefore I decided it would be best to use a MySQL database that they could share by making remote connections.

Why use MySQL?

The main advantage is as I have already mentioned, having a central MySQL database allows you to connect all your sites directly to it and access the information. There are ways to do this in Microsoft Access but they are patchy at best. The other option would be to use MS SQL server although this doesn’t come cheap from any host.

Changing the code

Let’s say for example I have a MySQL database on a linux hosting account at www.examplelinux.com. And I have a website at www.examplewindows.com that I want to connect with. Luckily connecting to MySQL is similar to any other connection except we just need to make a few changes.

The first is obvious; the connection script needs to be changed as we are accessing MySQL rather than an Access database. The second are certain changes in the scripts to make sure we don’t end up with any MySQL errors.

A typical DNS less connection would be something like:

Driver={Microsoft Access Driver (*.mdb)}; DBQ=" + Server.MapPath("/Conndb/springer1.mdb")

Whereas a connection to MySQL would look more like:

Driver={MySQL ODBC 3.51 Driver}; Server=examplelinux.com; Database=dbname; UID=username; PASS=password

To do this your server needs to have the MySQL driver on it. You can download it from http://www.mysql.com/downloads/index.html. You can also use a DNS connection if you have one which makes things considerably simpler:

DSN=linuxexampledns

All you need to do is replace the connection line you currently use with the new one modifying the username, password and name of the database you are going to use on your target server.

Further modifications

To make the ASP code work with MySQL there are a few other modifications you need to make with your code. The problem arises from the use of the ‘ character. Where Access is ok with it, MySQL will bring up a nice big error message.

Luckily a bit of PHP style code can come to the rescue. If you are familiar with PHP, you will know you can remove the significance of a character using \ before it. Therefore a quick replace function does the trick

Replace(string, "'", "\'")

So for instance a select command would go from:

SELECT * FROM hobbies WHERE firstname = '" + (users.Fields.Item("firstname").Value) + "' ORDER BY name ASC

And changed to:

SELECT * FROM hobbies WHERE firstname = '" + Replace((users.Fields.Item("firstname").Value) ,"'","\'") + "' ORDER BY name ASC

Setting up the server

Once the modifications to the code have been made you can get on with setting up the server to accept the requests. First of all you need to allow the scripts to access the database.

In CPanel goto MySQL Database and scroll down to access hosts: then add in the IP address of www.windowsexample.com. If you can’t find it out, simply run the scripts and it will bring you up an access denied message containing the IP address you are trying to access the database from.

In Direct Admin goto MySQL Databases, click on the database and then you can enter the IP address in to the access hosts form near the bottom. If you can access the privileges section in phpMyAdmin directly you can also do it from there as you can set for each user what access host the user can use.

The only other problem is getting the contents of your Access database to your MySQL server. The easiest way I found to do this way to set up a DNS connection to the MySQL server on my local machine, though you may be able to do this directly to the server providing you grant yourself access, and then going into Access and Exporting it.

File > Export then open the drop down menu at the bottom and and scroll to the bottom of the list until you see ODBC Databases (). This will close the export window and prompt you to enter the name of what you want to call it when you export it. Most likely it will be best to leave the default here.

Then it will come up with a box asking you to select a data source. Select the machine data source tab and find your DNS connection on the list then click ok and your done.

Conclusion

Switching your database from Access to MySQL is a hassle – you need a Linux server, code changes and connection scripts. However if your sites need to share a database its a far cheaper option that using MS SQL.