I am trying to display random banner each time the user refresh the page. The problem I am facing is that first banner to be displayed again and the banner fetch from data base. I am biegner in php..so suggested the code for banner refresh.
You could use PHP's rand function, setting the minimum to 0 and the maximum to the number of rows - 1, which would be used to select the banner at random.
Here's how I would do it, assuming that you're using a MySQL database (obviously you'll need to replace the MySQL parameters with your own):
$conn = mysql_connect("localhost", "username", "password");
$db = mysql_select_db("database_name_here", $conn);
$query = mysql_query("SELECT * from banner_table);
$max = mysql_num_rows($query) - 1;
$image = mysql_result($query, rand(0, $max), "Image_Url_Column");
Then wherever your image is contained:
<img src="<?php echo $image; ?>" alt="Banner image" />
Or if you're outputting the whole element in PHP:
echo "<img src=\"" . $image . "\" alt=\"Banner image\" />";
Update: If 3 banners are displayed at the same time, perhaps you could do something like this:
$conn = mysql_connect("localhost", "username", "password");
$db = mysql_select_db("database_name_here", $conn);
$query = mysql_query("SELECT * from banner_table);
$rows = mysql_num_rows($query);
$bannerToRetrieve; //the banner (database row number) to be retrieved from database
$alreadyRetrieved = array(); //holds values of previous numbers generated by rand() so the same banner isn't output again
for($i = 0; $i < 3; $i++)
{
//Only set $bannerToRetrieve to a row that hasn't already been called (stored in $alreadyRetrieved)
do
{
$bannerToRetrieve = rand(0, $rows - 1);
}
while(in_array($bannerToRetrieve, $alreadyRetrieved)); //if number is in array, it will generate another number
$image = mysql_result($query, $bannerToRetrieve, "Image_Url_Column");
echo "<img src=\"" . $image . "\" alt=\"Banner image\" />";
$alreadyRetrieved[] = $bannerToRetrieve;
}
And the $image variable represents the file name or perhaps URL of the image file to be loaded e.g. "banner1.png". Is this how you have designed the system?