php mysql留言板实现
创建数据库表
使用MySQL创建一个名为messages的表,包含字段:id(主键自增)、username(留言者名称)、content(留言内容)、created_at(留言时间)。
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
连接数据库
在PHP中通过PDO或MySQLi连接数据库。以下是PDO连接示例:
<?php
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
提交留言表单
创建HTML表单用于提交留言数据,表单提交到submit.php处理:
<form action="submit.php" method="post">
<input type="text" name="username" placeholder="Your name" required>
<textarea name="content" placeholder="Your message" required></textarea>
<button type="submit">Submit</button>
</form>
处理表单提交
在submit.php中接收表单数据并插入数据库:
<?php
require 'db_connection.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;
}
?>
显示留言列表
从数据库查询留言并显示:
<?php
require 'db_connection.php';
$stmt = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($messages as $message) {
echo "<div class='message'>";
echo "<h3>" . htmlspecialchars($message['username']) . "</h3>";
echo "<p>" . htmlspecialchars($message['content']) . "</p>";
echo "<small>" . $message['created_at'] . "</small>";
echo "</div>";
}
?>
添加分页功能
对于大量留言,可以添加分页:
$perPage = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$total = $pdo->query("SELECT COUNT(*) FROM messages")->fetchColumn();
$totalPages = ceil($total / $perPage);
$stmt = $pdo->prepare("SELECT * FROM messages ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $perPage, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
防止SQL注入
始终使用预处理语句处理用户输入,避免直接拼接SQL语句:
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (:username, :content)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':content', $content);
$stmt->execute();
添加删除功能
为管理员添加删除留言功能:
if (isset($_GET['delete'])) {
$id = (int)$_GET['delete'];
$stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
$stmt->execute([$id]);
header("Location: index.php");
exit;
}
样式优化
添加CSS样式美化留言板:
.message {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
}
.message h3 {
margin-top: 0;
}






