<?php
// 配置数据库连接
$host = 'localhost';
$db = 'ad_database';
$user = 'root';
$pass = 'password';
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
// 创建 PDO 实例
try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo '连接失败: ' . $e->getMessage();
exit;
}
// 获取广告列表
$sql = 'SELECT * FROM ads WHERE status = 1 ORDER BY RAND() LIMIT 5';
$stmt = $pdo->query($sql);
$ads = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 处理广告点击
if (isset($_GET['ad_id'])) {
$ad_id = (int)$_GET['ad_id'];
$updateSql = 'UPDATE ads SET clicks = clicks + 1 WHERE id = :id';
$updateStmt = $pdo->prepare($updateSql);
$updateStmt->execute(['id' => $ad_id]);
header('Location: ' . $_GET['url']);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>广告轮播</title>
<style>
.ad-container { position: relative; width: 100%; max-width: 800px; margin: auto; }
.ad-image { width: 100%; display: none; }
</style>
</head>
<body>
<div class="ad-container">
<?php foreach ($ads as $ad): ?>
<a href="?ad_id=<?php echo $ad['id']; ?>&url=<?php echo urlencode($ad['url']); ?>" target="_blank">
<img src="<?php echo $ad['image']; ?>" alt="<?php echo $ad['alt']; ?>" class="ad-image">
</a>
<?php endforeach; ?>
</div>
<script>
const ads = document.querySelectorAll('.ad-image');
let currentIndex = 0;
function showAd(index) {
ads.forEach((ad, i) => {
ad.style.display = i === index ? 'block' : 'none';
});
}
function nextAd() {
currentIndex = (currentIndex + 1) % ads.length;
showAd(currentIndex);
}
showAd(currentIndex);
setInterval(nextAd, 5000); // 每5秒切换广告
</script>
</body>
</html>
该 PHP 脚本实现了一个广告轮播系统,结合了用户点击追踪功能。系统从 MySQL 数据库中随机选择五个活跃广告进行展示。用户点击广告时,广告的点击量会更新到数据库,并且用户会被重定向到广告目标 URL。前端通过 JavaScript 实现广告的自动切换,每隔 5 秒切换一次广告。整体实现包括广告展示、点击追踪和动态广告切换的功能。