I have a loop that echos a list of links pulled from a database but I would like to track how many times each link listed is click.
form
link1
link2
link3
link4
link5
to
link1 (2)
link2 (7)
link3 (3)
link4 (4)
link5 (1)
So, each time link 1 is clicked, the amount of times that link 1 is clicked should be recorded and displayed next to the link.
This is the code I have so far.
echo "<table>";
while($row = mysql_fetch_array($result)){
//echo "<tr><td>" . $row['title'] . "</td><td>" . $row['url'] . "</td></tr>";
echo "<tr><td> <a href='" . $row['url'] . "' ' target='_blank'>" . $row['title'] . "</a> </td></tr>";
}
echo "</table>";
You can use a javascript function for managing all clics
var counter = {};
function manageClicks(url) {
if (! counter[url]) counter[url] = 0;
counter[url] ++;
alert('you clicked '+counter[url]+' '+url);
// return location.href = url;
return false;
}
<p>
Click some link:
</p>
<a href="#" onclick='manageClicks("url1")'> url1 </a><br>
<a href="#" onclick="manageClicks('url2')"> url2 </a><br>
<a href="#" onclick="manageClicks('url3')"> url3 </a><br>
</div>
You could do something like this to save it persistently. This is just an basic idea with a little bit of code. I did not test it.
Also you need a mapping to your link and the unique id to get the right cell in your database.
The frontend stuff:
<a href="http://yoururl.com/" onclick="handleLinkClick(this, 'a-unique-id')">
Your link <span class="counter">(<?php echo getLogCount('a-unique-id') ?></span>)
</a>
Now if a user clicks the link you could do this:
function handleLinkClick(element, urlId) {
$.ajax({
url: '/logurl.php',
method: 'POST',
data: {
id: urlId
}
});
// Count up immediately. You could also wait for a valid response.
var counterEl = element.querySelector('.counter');
var currentCount = parseInt(counterElement.innerHTML);
counterEl.innerHTML = (currentCount + 1).toString();
}
The backend stuff:
For the "getLogCount" you could define a function, which returns the clicks from your database (with PHP):
function getLogCount($urlId) {
$result = 0;
// @todo: Request to the database and get the count of the "$urlId".
// And save the result it in "$result"
return $result;
}
Now to log the click of the user in the database your "logurl.php" file could look like this:
$urlId = intval($_POST['id']);
// @todo: Update/Create a new entry in the database for the urlId.
// Maybe the columns could look something like: urlId (unique), clicks
I hope this will help you a little bit with your problem.