每次用户刷新页面时,我都会尝试显示随机横幅。我面临的问题是第一个要再次显示的横幅和从数据库中获取横幅。我是php的biegner ..所以建议横幅刷新的代码。
答案 0 :(得分:0)
您可以使用PHP的rand函数,将最小值设置为0,将最大值设置为行数-1,这将用于随机选择横幅。
假设您正在使用MySQL数据库(显然您需要用自己的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;
}
$ image变量表示要加载的图像文件的文件名或URL,例如“banner1.png”。这是你设计系统的方式吗?