Welcome to my ASP Code Website

Traffic Counters and ASP



Just about every site enjoys traffic counters. It helps you easily know who is looking at what without digging through log files. You can watch it real time! But how do you make a traffic counter?

In essence, you want to store a "counter" for each page or page set on your site. This is exactly what databases were designed to do - store discreet points of information, let you update them easily, and then let you run all sorts of reports on the data.

So create a table called traffic, with a numerical column page_id, a text column page_name, and a numerical column hit_count. Create page IDs and names for every page or set of pages you want to track. Then initialize all the hit counts to 0.

Now, at the top of each page, throw in an ASP command of

PageID = X

where X is the ID of that page. You can give each page its own ID if you want, or you can give say all advertising pages the same ID if you don't really care which particular page the person was on.

Now create an include file, say inc_traffic.asp. This file will be included into every page on your website, and will count the traffic. The code in this page can look like this:

Set objCmd4 = Server.CreateObject ("ADODB.Command")
SQLText = "update traffic set hit_count = hit_count + 1 where page_id = " & PageID
objCmd4.ActiveConnection = strConnect
objCmd4.CommandType = &H0001
objCmd4.CommandText = SQLText
objCmd4.Execute intRecords
Set objCmd4 = Nothing

That's it! Now every time one of your pages loads, it will have a PageID, and this include file will increment the page hit counter by one. You can write all sorts of real-time reporting pages to show you your traffic for the entire site, your top 10 pages, your least visited pages, and so on. If you add a "page_category" field, you can even do reporting on your pages by the category of page. That's the beauty of ASP, your imagination is the limit!

ASP Utility Code