PHP Banner Rotator Tutorial

Ranked #1,626 in Internet, #95,035 overall

Creating a php banner rotation script

In this tutorial we'll be creating a php banner rotator. What this basicly will be is a script that uses banners stored inside of a database table and shows a random one and this way creates a rotation of banners on one webpage. Also we'll keep log of the amount of views a banner has received and we'll set a max amount of views for each banner.

Preview: Click here.

Creating the database

We'll start with creating the database for the script. We'll use the database "webcodez". If you do not have a database with that name, create it. It's ok to give it any other name you desire, as long as you apply those changes correctly to our script.

Our script will need to save 7 things for each banner: the image url, link url (page to go to upon click on the banner), the location to display the banner on, views and max amount of views the banner may receive. We'll create a database table to store these info into: we'll call the fields: img_url, link_url, location, views, max_views and we'll have one more field called id.

SQL

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

CREATE TABLE IF NOT EXISTS `banners` (
`id` int(250) NOT NULL AUTO_INCREMENT,
`img_url` varchar(250) NOT NULL,
`link_url` varchar(250) NOT NULL,
`location` varchar(250) NOT NULL,
`views` int(11) NOT NULL,
`max_views` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `banners` (`id`, `img_url`, `link_url`, `location`, `views`, `max_views`) VALUES
(1, 'http://img856.imageshack.us/img856/4108/bannerct.png', 'http://www.squidoo.com/lensmaster/webcodez', '*', 4, 1000),
(2, 'http://www.istad.org/lenses/buttons-banners/squidoo-banner-teal.gif', 'http://www.squidoo.com', '*', 4, 1000);

Creating the banner rotation script

We'll first create a config file for our script which basicly contains the database connection:

config.php

<?php

/*
DB CONFIG
*/

$db['server'] = "localhost";
$db['user'] = "root";
$db['pass'] = "";
$db['name'] = "webcodez";

/*
DB CONNECTION
*/

mysql_connect($db['server'], $db['user'], $db['pass']);
mysql_select_db($db['name']);

?>

We created an array $db containing the database connection data and then used mysql_connect and mysql_select_db to establish a connection with the MySQL database. We could've done that as well inside of the rotator file ( establishing the actual connection ) but that's up to you if you prefer to do it instantly within the config file or do it for each file that requires it.

Next we'll start creating the actual rotator script. We'll simply create one function that gets the banner to display. We'll call it "displayBanner":

rotator.php

function displayBanner($location) {
}

It requires 1 parameter to be given: the location to display the banner, which determines which banners may be displayed (/are rotated). We'll indicate a location equal to "*" as any location. Thus we'll display the banners with location = $location OR location = "*". Because these are the banners that may be displayed at the current page ( supplied in $location to the function upon calling it ). The query that gets the banner will thus atleast have this WHERE clause:

... WHERE location = '$location' OR location = '*'

thus we get the following query:

SELECT * FROM banners WHERE location = '$location' OR location = '*'

But this would select ALL the banners that may be displayed on the current page. We only want 1 though, a random one. To do this, we can use the following 'trick': adding a random order to the query using ORDER BY RAND():

<?php

function displayBanner($location) {

$get_banner = mysql_query("SELECT * FROM banners WHERE location = '$location' OR location = '*' ORDER BY RAND()");

}

?>

We stored the query inside of a variable $get_banner. Now we'll use mysql_fetch_assoc to get 1 banner entry from the query ( which will be a random one as we ordered them randomly ).

<?php

function displayBanner($location) {

$get_banner = mysql_query("SELECT * FROM banners WHERE location = '$location' OR location = '*' ORDER BY RAND()");
$banner = mysql_fetch_assoc($get_banner);

}

?>

We now have all the info from the randomly selected banner inside of an array $banner ( containing all the table fields: id, img_url, link_url, etc. as sub-variable to the array ). We can now thus use these to display the banner using the HTML img tag and a href tag to link it:

<?php

function displayBanner($location) {

$get_banner = mysql_query("SELECT * FROM banners WHERE location = '$location' OR location = '*' ORDER BY RAND()");
$banner = mysql_fetch_assoc($get_banner);

echo "<a href='".$banner['link_url']."'><img src='".$banner['img_url']."'></a>";

}

?>

All that's left to do now is to update the banner that has been displayed by adding 1 to the amount of views of the banner. Here comes the 'id' field useful as we got the id of the banner we selected in $banner['id'] and as each banner has its own unique id, we can now easily UDPATE the banner with the id equal to $banner['id']:

rotator.php

<?php

function displayBanner($location) {

$get_banner = mysql_query("SELECT * FROM banners WHERE location = '$location' OR location = '*' ORDER BY RAND()");
$banner = mysql_fetch_assoc($get_banner);

echo "<a href='".$banner['link_url']."'><img src='".$banner['img_url']."'></a>";

$update_banner = mysql_query("UPDATE banners SET views = views+1 WHERE id = '".$banner['id']."' ");

}

?>

And that's it! We now got our own banner rotation script. The usage will be shown below.

Usage

To use our script, we can simply include our banner rotation script ( rotator.php ) into any webpage we'd like to use it. We'll also need to include our config file which establishes a connection with the database. Then all we have to do is call our function displayBanner and supply it with the location of the current webpage ( stored in $_SERVER['PHP_SELF'] ) :

<?php
/*
My Webpage!
*/

include_once("config.php");
include_once("rotator.php");

displayBanner($_SERVER['PHP_SELF']);
?>



To add a banner you can simply create a query like this:

mysql_query("INSERT INTO banners(img_url, link_url, location, max_views)VALUES('image url here', 'link url here', 'location', max views here) ");

This can also be done through phpmyadmin or whatever software you/your webhost uses for database management. In this tutorial we used $_SERVER['PHP_SELF'] as location reference for each file, so you'll have to use that format for the location of each file.

You might also like ...

Loading

Comments & Questions

  • rocky Mar 24, 2012 @ 2:16 am | delete
    thanks for this i will try
    mobile prices in Pakistan

by

webcodez

"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."

webcodez
GameHeroes
more »

Feeling creative? Create a Lens!