留言板实现php
留言板实现(PHP)
数据库设计
创建一个MySQL数据库表存储留言信息,基本字段包括留言ID、用户名、留言内容、留言时间等。
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
数据库连接
创建config.php文件存放数据库连接信息。
<?php
$host = 'localhost';
$dbname = 'message_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());
}
?>
提交留言
创建submit.php处理表单提交。
<?php
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
$content = htmlspecialchars($_POST['content']);
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (?, ?)");
$stmt->execute([$username, $content]);
header("Location: index.php");
exit;
}
?>
显示留言
创建index.php显示留言列表。
<?php
require 'config.php';
$stmt = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="submit.php" method="post">
<input type="text" name="username" placeholder="用户名" required>
<textarea name="content" placeholder="留言内容" required></textarea>
<button type="submit">提交</button>
</form>
<div class="messages">
<?php foreach ($messages as $message): ?>
<div class="message">
<h3><?php echo $message['username']; ?></h3>
<p><?php echo $message['content']; ?></p>
<small><?php echo $message['created_at']; ?></small>
</div>
<?php endforeach; ?>
</div>
</body>
</html>
安全增强
对用户输入进行过滤和验证,防止XSS和SQL注入。
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
分页功能
添加分页功能处理大量留言。
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 5;
$offset = ($page - 1) * $limit;
$stmt = $pdo->prepare("SELECT * FROM messages ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $limit, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
样式美化
添加CSS样式提升页面美观度。

<style>
body { font-family: Arial, sans-serif; }
.messages { margin-top: 20px; }
.message { border-bottom: 1px solid #eee; padding: 10px 0; }
textarea { width: 100%; height: 100px; }
</style>
这个实现包含了留言板的基本功能,可以根据需要进一步扩展如用户注册登录、留言回复、图片上传等功能。






