<?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';
$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 { width: 100%; max-width: 600px; margin: auto; }
.ad-image { width: 100%; }
</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>
</body>
</html>
这个 PHP 脚本展示了一个广告系统,广告数据存储在 MySQL 数据库中。用户点击广告时,广告的点击数会在数据库中更新,同时用户会被重定向到广告目标 URL。数据库连接使用 PDO,并设置了错误处理模式。广告展示部分通过 PHP 动态生成 HTML 代码,并且使用了简单的 CSS 来控制广告的样式。