2012-05-05 52 views
0

我试图每次刷新页面时显示随机横幅。我面临的问题是第一个横幅将再次显示,并从数据库中提取横幅。我biegner在PHP ..所以建议横幅刷新的代码。横幅更新刷新

+1

到目前为止你写了什么代码? –

+0

请在此发布您的代码。我们可以为您提供建议。 – Dhruvisha

+0

可能这对你有帮助:http://www.phpbb.com/kb/article/adding-a-random-header-image/ – Dhruvisha

回答

0

您可以使用PHP的rand函数,将最小值设置为0,最大值设置为行数-1,这将用于随机选择横幅。

这是我会怎么做,假设你使用MySQL数据库(当然你需要用自己的来取代MySQL参数):

$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"); 

那么无论你的形象包含:

<img src="<?php echo $image; ?>" alt="Banner image" /> 

或者如果你在输出PHP整个元素:

echo "<img src=\"" . $image . "\" alt=\"Banner image\" />"; 

更新:如果3条横幅同时显示,也许你可以做这样的事情:

$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; 
} 

以及$图像变量表示的文件名或者是图像文件的URL将被加载例如“banner1.png”。这是你设计系统的方式吗?

+0

谢谢你的回复。但在我的网站的主页上的横幅来自数据库..在中间部分(宽度为80%),每次显示3条横幅时,我想这样做,当我刷新所有3条横幅变化并且横幅在1小时后显示..以及为什么要使用$ image变量。 。它的理由是什么,我不明白..plz解释..它紧急。 –

+0

@Alica_Casaligi我修改了我的答案,参见上文。 –

+0

thanx很多...其工作.... –