php实现电子公告牌
实现电子公告牌的基本功能
使用PHP和MySQL可以快速搭建一个电子公告牌系统。以下是一个基础实现方案:
数据库设计
创建名为notice_board的数据库,包含一个notices表:
CREATE TABLE notices (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
连接数据库
创建config.php文件处理数据库连接:
<?php
$host = 'localhost';
$dbname = 'notice_board';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("数据库连接失败: " . $e->getMessage());
}
?>
发布公告功能
创建create.php处理公告发布:
<?php
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = $_POST['title'];
$content = $_POST['content'];
$stmt = $pdo->prepare("INSERT INTO notices (title, content) VALUES (?, ?)");
$stmt->execute([$title, $content]);
header("Location: index.php");
exit;
}
?>
<form method="post">
<input type="text" name="title" placeholder="公告标题" required>
<textarea name="content" placeholder="公告内容" required></textarea>
<button type="submit">发布公告</button>
</form>
显示公告列表
创建index.php显示所有公告:
<?php
require 'config.php';
$stmt = $pdo->query("SELECT * FROM notices ORDER BY created_at DESC");
$notices = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<h1>电子公告牌</h1>
<a href="create.php">发布新公告</a>
<?php foreach ($notices as $notice): ?>
<div class="notice">
<h2><?= htmlspecialchars($notice['title']) ?></h2>
<p><?= nl2br(htmlspecialchars($notice['content'])) ?></p>
<small>发布时间: <?= $notice['created_at'] ?></small>
</div>
<?php endforeach; ?>
安全增强措施
为防止XSS攻击,所有输出内容都应使用htmlspecialchars()过滤:
$title = htmlspecialchars($_POST['title'], ENT_QUOTES, 'UTF-8');
使用预处理语句防止SQL注入:
$stmt = $pdo->prepare("INSERT INTO notices (title, content) VALUES (:title, :content)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':content', $content);
$stmt->execute();
扩展功能建议
添加用户认证系统限制发布权限:
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
实现公告编辑和删除功能:
// 删除公告
$stmt = $pdo->prepare("DELETE FROM notices WHERE id = ?");
$stmt->execute([$id]);
// 更新公告
$stmt = $pdo->prepare("UPDATE notices SET title = ?, content = ? WHERE id = ?");
$stmt->execute([$title, $content, $id]);
添加分页功能提升性能:

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare("SELECT * FROM notices ORDER BY created_at DESC LIMIT :offset, :perPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
这个基础实现可以根据需求进一步扩展,如添加分类标签、评论功能或附件上传等。






