1. Home
  2. Computing & Technology
  3. PHP / MySQL

Counting Outbound Clicks

See which links get clicked through and how often

By Angela Bradley, About.com

This is a simple little bit of code that can be used to count links going off your site. It was originally written to count click-throughs for a 'Top Sites' program, but could be useful for any site that needs to count how many outgoing links are clicked, and to what pages.

This code can be saved as add.php. It assumes that you have a database in place where the url's of sites are stored along with a unique site ID number. We use this ID number to reference the site in links and in the tracking. The auto-incriment field type tends to work best for this in MySQL.

<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());

//Adds to the click count for a particular link
mysql_query("UPDATE table_name SET out = out + 1 WHERE ID = $id")or die(mysql_error());

//Retrieves information
$data = mysql_query("SELECT * FROM table_name WHERE ID = $id") or die(mysql_error());
$info = mysql_fetch_array($data);

//redirects them to the link they clicked
header( "Location:" .$info['URL'] );
?>
The link on your actual page would look like this:
<a href="http://www.yoursite.com/out.php?id=4">Some Website</a>
The link above would add 1 to the count on the site with the ID of 4, and then direct the users to the website.
More PHP / MySQL Quick Tips

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Step By Steps
  5. PHP Link Tracking - PHP Outbound Links - PHP Link Count

©2008 About.com, a part of The New York Times Company.

All rights reserved.