php实现发帖功能
数据库表设计
创建帖子表(如 posts)存储发帖内容,字段可包含:
id:自增主键title:帖子标题(VARCHAR)content:帖子内容(TEXT)user_id:发帖用户ID(关联用户表)created_at:发帖时间(TIMESTAMP)
SQL示例:
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
表单提交处理
前端表单需包含标题和内容输入框,通过POST方法提交:
<form action="submit_post.php" method="post">
<input type="text" name="title" placeholder="标题" required>
<textarea name="content" placeholder="内容" required></textarea>
<button type="submit">发布</button>
</form>
PHP后端处理
创建 submit_post.php 文件,验证并存储数据:
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
// 获取表单数据并过滤
$title = htmlspecialchars($_POST['title']);
$content = htmlspecialchars($_POST['content']);
$user_id = 1; // 假设当前用户ID为1
// 插入数据库
$stmt = $db->prepare("INSERT INTO posts (title, content, user_id) VALUES (?, ?, ?)");
$stmt->execute([$title, $content, $user_id]);
// 跳转回首页或提示成功
header("Location: index.php");
exit;
?>
安全性增强
- 使用预处理语句防止SQL注入。
- 对用户输入进行过滤(如
htmlspecialchars)。 - 添加CSRF令牌防护(如生成随机token并验证)。
文件上传扩展
若需支持图片上传,可在表单中添加文件字段:
<input type="file" name="image" accept="image/*">
后端处理文件上传:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
错误处理
添加异常捕获和用户反馈:
try {
$stmt->execute([$title, $content, $user_id]);
} catch (PDOException $e) {
die("发帖失败: " . $e->getMessage());
}






