3/25/2010

Building a Fair and Convincing Banner Rotator

I have seen several tutorials how to write a banner rotator online. They are technically correct but looks like the programmers haven't really put their rotators in real environment. They assume that selecting a random banner from the list (or database) will do the work and show the banners equally. Good idea and correct in general.

But as I have run such a rotator in a live site where more than 7-8 banners were rotating, I know this isn't a good enough solution. Why so? Although computer random algos or the SQL RAND() ensure all banners will be shown almost the same number of times in the long run, during 10-20 page refreshes you can keep getting the same 3-4 banners and other ones may not appear at all. This is a problem because the clients who purcased banners complain "Hey, I refreshed more than 10 times and my banner isn't showing even once!!!". Go explain them about random computer algos and that someone might be seeing their banner at the same in some other computer at the other side of the globe.

To avoid such problem, we need not only fair, but also convincing banner rotator - such that will show you the banners equal times when you are refreshing the page.

Let's see what we need:

1. A list or DB table of banners
2. Fair selection
3. Counting the views and clicks

That's in short. We will write two PHP scripts - one will select and output the banner (we'll assume you'll put it in an iframe or will add some other useful stuff to it so you can have a full page with content); and one will redirect the visitors to the targed URL and count the clicks. Let's start:

1. A list of banners

Because we need to save the number of clicks to our banners we'll use a MySQL DB table:

Table banners:
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
image VARCHAR(255) NOT NULL,
url VARCHAR(255) NOT NULL,
clicks INT UNSIGNED NOT NULL;

In the real life you will probably have also a field for customer name, email etc. but let's not worry about this now.

2. Fair selection
This is the most interesting part. Let's call our script rotator.php. It will need not only to select a supposingly random banner, but to ensure that the rotation will be equal even for every single user who is seeing the page. Here's how to do this: we will store the IDs of the banners shown in a session. When selecting, we will make sure we get a random banner from those which have not been shown yet. When all the banners have been shown once in the current session, we'll empty the data and start over. Let's talk code:

rotator.php

// in this array we'll store the shown banners
if(!isset($_SESSION['banner_ids'])) $_SESSION['banner_ids']=array(0);

// let's built the conditional SQL now
$id_sql=implode(",",$_SESSION['banner_ids']);

// now select random banner instead of these that were shown
$q="SELECT * FROM banners WHERE id NOT IN ($id_sql) ORDER BY RAND() LIMIT 1";
$banner=mysql_fetch_array(mysql_query($q));

// enter this banner ID in the already seen ones
$_SESSION['banner_ids'][]=$banner['id'];

// now we need to check whether all the banners were shown once
$q="SELECT COUNT(id) FROM banners";
$num_banners=mysql_fetch_row(mysql_query($q));

// we use "<" because our session array always contains one more ID - the zero which is
// there to prevent mysql error
if($num_banners[0] < sizeof($_SESSION['banner_ids']))
{
unset($_SESSION['banner_ids']);
}

// that's it! now just display the banner:
echo "<a href='go.php?id=$banner[id]'><img src='$banner[image]'></a>";


Counting the views and clicks
Now this is pretty straightforward:

go.php

// prevent hacking
if(!is_numeric($_GET['id'])) exit;

// select banner
$q="SELECT * FROM banners WHERE id='$_GET[id]'";
$banner=mysql_fetch_array(mysql_query($q));

// update clicks
$q="UPDATE banners SET clicks=clicks+1 WHERE id='$banner[id]'";
mysql_query($q);

// redirect
header("Location: $banner[url]");


That's all!

50 comments:

  1. Boss very very thanks for this article.

    ReplyDelete
  2. dear it is very hard to learn like this.
    please can you define this scripting by video ?

    facebook app | facebook developer

    ReplyDelete
  3. Building fair and convincing banner is shown on the post here. Read all about it
    CD distribution

    ReplyDelete
  4. Really helpful blog for the naïve users. Should try out the code given in the blog!
    DVD printing

    ReplyDelete
  5. Good tips..Its a good effort thanks for posting..
    best dissertation topics

    ReplyDelete
  6. Nice blog...Very useful information is providing by ur blog..here is a way to find

    Php training institute in bangalore

    ReplyDelete
  7. your blog is very nice .i like it so much.thank u for sharing.PHP

    ReplyDelete
  8. Thanks for sharing this wonderful information.Its very nice blog PHP

    ReplyDelete
  9. Thanks for sharing the valuable information here. So i think i got some useful information with this content. Thank you and please keep update like this informative details.


    School Website Designs

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Ελπίζω ότι θα έχετε καλύτερα και καλύτερα άρθρα. Σας εύχομαι μια ωραία νέα μέρα

    bồn mát xa chân

    chậu ngâm chân giá rẻ

    máy ngâm chân giải độc

    bồn massage ngâm chân

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Có lẽ cần phải trải qua tuổi thanh xuân( Phương pháp học toán tư duy ) mới có thể hiểu được tuổi xuân là khoảng thời gian ta( dạy trẻ học toán tư duy ) sống ích kỷ biết chừng nào. Có lúc nghĩ, sở dĩ tình yêu cần phải đi một vòng tròn lớn như vậy, phải trả một cái giá quá đắt như thế,( Học toán tư duy có tốt không ) là bởi vì nó đến không đúng thời điểm. Khi có được( Toán mầm non ) tình yêu, chúng ta thiếu đi trí tuệ. Đợi đến khi( Bé học đếm số ) có đủ trí tuệ, chúng ta đã không còn sức lực để yêu một tình yêu thuần khiết nữa.

    ReplyDelete
  14. Дээд чанар бол зүгээр л( đá ruby thiên nhiên ) санаатай биш юм. Энэ нь өндөр( đá ruby nam phi ) түвшний төвлөрөл, тусгай хүчин( Đá Sapphire ) чармайлт, ухаалаг ( đá sapphire hợp mệnh gì )чиг баримжаа, чадварлаг туршлага, ( đá tourmaline đen)саад тотгорыг даван туулах( khám phá nhẫn cưới đá quý thiên nhiên ) боломжийг хардаг.

    ReplyDelete
  15. Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, WhatsApp, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now

    more details click the link now

    [url]https://www.webdschool.com/web-development-course-in-chennai.html[/url]

    ReplyDelete
  16. It’s really a great and useful piece of information. I’m glad that you just shared this helpful information with us.
    If anyone want to know about Data science course in pune , best data science course in pune with placement, please visit the site
    Please stay us informed like this.

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Well written articles like yours renews my faith in today’s writers.
    You’ve written information I can finally agree on and use.
    Thank you for sharing.칼로커트 가격

    ReplyDelete
  19. Even after completing an essay, students are frequently refused. This is the case since essays are graded on a variety of criteria. The majority of students are rejected because they fall into the plagiarism trap. SourceEssay and other essay proofreading companies have stepped forward to help students with their assignments and provide university assignment help gold coast
    Students who are unable to perform well in their academics are more likely to drop out of university, according to multiple studies. Students may now acquire low-cost assignment assistance from services like SourceEssay, which is helping to reduce the number of students dropping out of universities, colleges, and schools. With the assistance of teams of skilled and dedicated online assignment instructors, students can learn how to improve their grades. All you have to do is contact us for low-cost essay writing help. Here are some tips for writing an essay that will help you get a decent grade.

    ReplyDelete