ProDraz
ProDraz

Reputation: 1281

How to track image/banner clicks/views with PHP/MySQL

I wonder how could I modify this existing code in order to track image/banner clicks/views? Is this even possible with just PHP or do you need to use jQuery (ajax)?

I have bannerClicks and bannerViews inside tblbanners in my MYSQL table.

This is the code to generate image/banner:

    $query91 = 'SELECT * FROM tblbanners WHERE tblbanners.bannerStatus!=\'1\'';
    $result91 = full_query ($query91);

    $bannerCounter = 1;
    while ($data91 = mysql_fetch_array ($result91))
    {

        $ID = $data91['ID'];
        $bannerName = $data91['bannerName'];
        $bannerLocation = $data91['bannerLocation'];
        $bannerUrl = $data91['bannerUrl'];      

        $bannerCode[$bannerCounter] = '<a id="' . $ID . '" class="banner-url" href="' . $bannerUrl . '" target="_blank"><img alt="' . $bannerName . '" src="banners/' . $bannerLocation . '" width="100px" height="200px" /></a>';
        $bannerCounter++;
    }

    $bannerAdTotals = $bannerCounter - 1;

    if($bannerAdTotals > 1)
    {
       mt_srand((double)microtime() * 1234567);
       $bannerPicked = mt_rand(1, $bannerAdTotals);
    }
    else
    {
       $bannerPicked = 1;
    }

    $bannerAd = $bannerCode[$bannerPicked];

    print $bannerAd;

Upvotes: 0

Views: 2199

Answers (1)

Martin Bean
Martin Bean

Reputation: 39389

You can either use JavaScript, or intercept clicks. To intercept clicks, presuming you store the banner URL in the database, you can just set up a PHP script to intercept the click, track the click, and then redirect. Something as simple as:

<?php

$sql = "SELECT `url` FROM `banners` WHERE `id` = :banner_id LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':banner_id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$banner = $stmt->fetchObject();

$sql = "INSERT INTO `clicks` (`banner_id`) VALUES (1)";
$res = $db->exec($sql);

header('Location: ' . $banner->url);

Obviously you'll need to instantiate your database connection/object, change any database table and column names, and any validation.

With this approach, when you display your banner you then do this instead when selecting a banner from your database:

<a href="track_click.php?id=<?php echo $banner->id; ?>">
  <img src="<?php echo $banner->img; ?>" alt="<?php echo $banner->alt; ?>" />
</a>

Upvotes: 2

Related Questions