php实现发帖
PHP 实现发帖功能
要在 PHP 中实现发帖功能,通常需要结合数据库操作(如 MySQL)和前端表单提交。以下是实现发帖功能的关键步骤:
数据库表设计
创建一个帖子表(posts)存储发帖内容,基本字段如下:
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
前端表单
创建 HTML 表单用于提交帖子内容:
<form action="post_submit.php" method="post">
<input type="text" name="title" placeholder="标题" required>
<textarea name="content" placeholder="内容" required></textarea>
<input type="text" name="author" placeholder="作者">
<button type="submit">发布</button>
</form>
后端处理
创建 post_submit.php 处理表单提交:
<?php
// 连接数据库
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取表单数据
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_POST['author'];
// 防止 SQL 注入
$title = $conn->real_escape_string($title);
$content = $conn->real_escape_string($content);
$author = $conn->real_escape_string($author);
// 插入数据
$sql = "INSERT INTO posts (title, content, author) VALUES ('$title', '$content', '$author')";
if ($conn->query($sql) === TRUE) {
echo "发帖成功";
} else {
echo "错误: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
安全性增强
为提高安全性,可以使用预处理语句(Prepared Statements):
$stmt = $conn->prepare("INSERT INTO posts (title, content, author) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $title, $content, $author);
$stmt->execute();
显示帖子
创建 posts.php 显示所有帖子:
$result = $conn->query("SELECT * FROM posts ORDER BY created_at DESC");
while ($row = $result->fetch_assoc()) {
echo "<h3>{$row['title']}</h3>";
echo "<p>{$row['content']}</p>";
echo "<small>作者: {$row['author']} | 时间: {$row['created_at']}</small>";
}
注意事项
- 确保对用户输入进行验证和过滤
- 在生产环境中使用 HTTPS 保护数据传输
- 考虑添加 CSRF 防护措施
- 对敏感操作进行权限验证







