How to count link clicks using php
Posted: Sun Feb 21, 2010 3:34 pm
This is a simple little bit of code that can be used to count links going off your site. This 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 link.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-increment field type tends to work best for this in MySQL.
The link on your actual page would look like this:
<a href="http://www.yoursite.com/link.php?id=7">Some Website</a>
The link above would add 1 to the count on the site with the ID of 7, and then direct the users to the website.
This code can be saved as link.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-increment field type tends to work best for this in MySQL.
Code: Select all
<?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'] );
?>
<a href="http://www.yoursite.com/link.php?id=7">Some Website</a>
The link above would add 1 to the count on the site with the ID of 7, and then direct the users to the website.