<?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;
}
// 处理广告数据
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
if ($_POST['action'] === 'add') {
$title = $_POST['title'];
$url = $_POST['url'];
$image = $_POST['image'];
$status = $_POST['status'];
$sql = 'INSERT INTO ads (title, url, image, status) VALUES (:title, :url, :image, :status)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
'title' => $title,
'url' => $url,
'image' => $image,
'status' => $status
]);
} elseif ($_POST['action'] === 'delete') {
$id = (int)$_POST['id'];
$sql = 'DELETE FROM ads WHERE id = :id';
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $id]);
}
}
}
// 获取广告列表
$sql = 'SELECT * FROM ads ORDER BY created_at DESC';
$stmt = $pdo->query($sql);
$ads = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>广告管理系统</title>
</head>
<body>
<h1>广告管理</h1>
<form method="post">
<h2>添加广告</h2>
<input type="hidden" name="action" value="add">
<label for="title">标题:</label>
<input type="text" name="title" id="title" required>
<label for="url">链接:</label>
<input type="text" name="url" id="url" required>
<label for="image">图片 URL:</label>
<input type="text" name="image" id="image" required>
<label for="status">状态:</label>
<select name="status" id="status">
<option value="1">启用</option>
<option value="0">禁用</option>
</select>
<button type="submit">添加广告</button>
</form>
<h2>广告列表</h2>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>标题</th>
<th>链接</th>
<th>图片</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($ads as $ad): ?>
<tr>
<td><?php echo $ad['id']; ?></td>
<td><?php echo htmlspecialchars($ad['title']); ?></td>
<td><?php echo htmlspecialchars($ad['url']); ?></td>
<td><img src="<?php echo htmlspecialchars($ad['image']); ?>" alt="<?php echo htmlspecialchars($ad['title']); ?>" width="100"></td>
<td><?php echo $ad['status'] == 1 ? '启用' : '禁用'; ?></td>
<td>
<form method="post" style="display:inline;">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?php echo $ad['id']; ?>">
<button type="submit">删除</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
此 PHP 代码示例实现了一个简单的广告管理系统后台。它允许用户添加和删除广告,并展示所有广告的列表。通过表单提交广告数据(包括标题、链接、图片 URL 和状态),系统会将广告保存到数据库中。用户也可以从广告列表中删除广告。这个系统的实现包括了基础的数据库操作、表单处理和前端展示,帮助广告开发者管理广告内容。