PHP Banner Rotator

So you’ve worked hard on your website, and now you want to rotate banners on your website and generate some cash. It’s time for a PHP Banner Rotator!

This code sample assumes you have a table named “banners” with at least two fields “SiteURL” and “BannerURL”. Which, shouldn’t need explaination as to what they are.

The Code

<?
$global_dbh = mysql_connect("localhost","username","password");
mysql_select_db("mydatabasename", $global_dbh);

$query = "SELECT * FROM `banners` ORDER BY RAND() LIMIT 1";
$result = mysql_query($query, $global_dbh);
$row = mysql_fetch_array($result);

echo "<A HREF=\"{$row["SiteURL"]}\" TARGET=\"_blank\"".
     " BORDER=\"0\">{$row["BannerURL"]}</A>";
?>

The Core
The core of the code is that SQL query:

$query = "SELECT * FROM `banners` ORDER BY RAND() LIMIT 1";

This uses the built in MySQL function RAND() to select one (LIMIT 1) random (ORDER BY RAND()) row from the table banners.

Including the Rotator
If you want to include a banner right inside a page, simply use an include statement:

<? include "rotator.php"; ?>

Including Remotely
The easiest way to include your banner rotator remotely is to include the rotator.php script by using and iframe. But first, you’ll want rotator.php to output an entire page, with all the basic parts of a page (,etc) Then put in the following style tag:

<STYLE>
body {margin: 0; }
</STYLE>

This will make sure only the banner is shown, and no whitespace. Next you’ll use the following iframe code:

<iframe width=’468′ height=60 scrolling=’no’ frameborder=’0′ framespacing=’0′ marginheight=’0′ marginwidth=’0′ border=’0′ hspace=’0′ vspace=’0′ align=’right’ src="rotator.php"></iframe>