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!

70 comments:

  1. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..
    php tutorial
    Thanks a lot..!

    ReplyDelete
  2. Boss very very thanks for this article.

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

    facebook app | facebook developer

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

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

    ReplyDelete
  6. NICE BLOG!!! Thanks for sharing useful information about FNT Softwre Solutions and being one of best Software Training institute in Bangalore we agree that this blog is very useful for the students are Searching for best software courses, I would really like to come back again right here for like wise good articles or blog posts. Thanks for sharing...PHP Training Bangalore .

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

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

    Php training institute in bangalore

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

    weblogic training in bangalore

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

    ReplyDelete
  11. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  12. I am glad to find your impressive way of writing the post.Thanks for sharing the post.Also
    see my blog Best Dot Net Training Academy in Chennai

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

    ReplyDelete
  14. My friend Suggest me this blog and I can say this is the best blog to get the basic knowledge.Thank you so much for this Selenium Training in Chennai

    ReplyDelete
  15. Well explained. Got to learn new things from your Blog on Appium.Appium training in chennai

    ReplyDelete
  16. 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
  17. Really Good blog post.provided a helpful information.keep updating...
    Digital marketing company in Chennai

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

    ReplyDelete
  19. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.
    Data Science Training in chennai at Credo Systemz | data science course fees in chennai | data science course in chennai velachery | data science course in chennai omr

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

    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
  21. This comment has been removed by the author.

    ReplyDelete
  22. 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
  23. Si el agua cae al lago, desaparecerá( phụ kiện tủ bếp ). Pero si cae a la hoja de( phụ kiện tủ áo ) loto, brillará como una joya. Caer igual pero( thùng gạo thông minh ) estar con alguien es importante.

    ReplyDelete
  24. Дээд чанар бол зүгээр л( đá 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
  25. Thanks for sharing
    We are the best piping design course in Hyderabad, India. Sanjary academy Offers Piping Design Course and Best Piping Design Training Institute in Hyderabad. Piping Design Institute in India Piping Design Engineering.
    Piping Design Course
    Piping Design Course in india
    Piping Design Course in hyderabad

    ReplyDelete
  26. Nice Information
    Sanjary kids is the best playschool, preschool in Hyderabad, India. Start your play school,preschool in Hyderabad with sanjary kids. Sanjary kids provides programs like Play group,Nursery,Junior KG,Serior KG,and Teacher Training Program.
    play school in hyderabad, India
    Preschool in hyderabad, India
    Preschool teacher training course in hyderabad, India
    pre and primary teacher training course in hyderabad,India
    early childhood teacher training course in hyderabad, India

    ReplyDelete
  27. Thanks for sharing information
    Best QA / QC Course in India, Hyderabad. sanjaryacademy is a well-known institute. We have offer professional Engineering Course like Piping Design Course, QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    QA / QC Course
    QA / QC Course in india
    QA / QC Course in hyderabad

    ReplyDelete
  28. 7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

    we have offered to the advanced syllabus course digital marketing for available join now

    more details click the link now

    [url]https://www.webdschool.com/digital-marketing-course-in-chennai.html[/url]

    ReplyDelete
  29. 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
  30. 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
  31. You can join the free orientation at Workday training institutes in Bangalore and they located at Workday training institutes in delhi. It is highly recommendable for you to enroll at Workday training institutes in UK and you can have a great market for jobs in USA so join this wonderful Workday training institutes in USA and in India this Workday training institutes in Noida is really best institute.

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

    ReplyDelete
  33. IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Projects for CSE It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    JavaScript Online Training in India

    JavaScript Training in India

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  34. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    workday online training
    best workday online training
    top workday online training

    ReplyDelete