要在不同的页面上显示随机图像且不重复,你可以采用以下步骤:
<?php
session_start();
// 假设你的数据库表名为 images,包含 id 和 path 字段
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取所有图像ID
$sql = "SELECT id FROM images";
$result = $conn->query($sql);
$allImages = [];
while ($row = $result->fetch_assoc()) {
$allImages[] = $row['id'];
}
// 移除已经显示过的图像ID
$displayedImages = isset($_SESSION['displayed_images']) ? $_SESSION['displayed_images'] : [];
$availableImages = array_diff($allImages, $displayedImages);
if (empty($availableImages)) {
// 如果所有图像都已显示过,重置会话
$_SESSION['displayed_images'] = [];
$availableImages = $allImages;
}
// 随机选择一个图像ID
$randomIndex = array_rand($availableImages);
$randomImageId = $availableImages[$randomIndex];
// 获取图像路径
$sql = "SELECT path FROM images WHERE id = $randomImageId";
$result = $conn->query($sql);
$imagePath = $result->fetch_assoc()['path'];
// 记录已显示的图像ID
$_SESSION['displayed_images'][] = $randomImageId;
$conn->close();
// 显示图像
echo "<img src='$imagePath' alt='Random Image'>";
?>
displayed_images
数组正确记录了已显示的图像ID。通过以上步骤和代码示例,你可以在不同的页面上显示随机图像且不重复。希望这对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云