php实现视频评论
实现视频评论功能的 PHP 方法
数据库设计
创建数据库表存储评论数据,表结构可包含以下字段:
CREATE TABLE video_comments (
id INT AUTO_INCREMENT PRIMARY KEY,
video_id INT NOT NULL,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (video_id) REFERENCES videos(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
评论提交处理
创建处理评论提交的 PHP 脚本:
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
// 获取POST数据
$videoId = $_POST['video_id'];
$userId = $_POST['user_id'];
$content = htmlspecialchars($_POST['content']);
// 插入评论
$stmt = $db->prepare("INSERT INTO video_comments (video_id, user_id, content) VALUES (?, ?, ?)");
$stmt->execute([$videoId, $userId, $content]);
// 返回成功响应
echo json_encode(['status' => 'success']);
?>
显示评论列表
创建获取并显示评论的 PHP 代码:
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
// 获取视频ID
$videoId = $_GET['video_id'];
// 查询评论
$stmt = $db->prepare("SELECT c.*, u.username FROM video_comments c JOIN users u ON c.user_id = u.id WHERE c.video_id = ? ORDER BY c.created_at DESC");
$stmt->execute([$videoId]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 输出评论
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<strong>' . htmlspecialchars($comment['username']) . '</strong>';
echo '<p>' . htmlspecialchars($comment['content']) . '</p>';
echo '<small>' . $comment['created_at'] . '</small>';
echo '</div>';
}
?>
前端交互
创建评论表单和AJAX提交:
<form id="comment-form">
<input type="hidden" name="video_id" value="<?php echo $videoId; ?>">
<input type="hidden" name="user_id" value="<?php echo $userId; ?>">
<textarea name="content" required></textarea>
<button type="submit">提交评论</button>
</form>
<script>
document.getElementById('comment-form').addEventListener('submit', function(e) {
e.preventDefault();
fetch('submit_comment.php', {
method: 'POST',
body: new FormData(this)
})
.then(response => response.json())
.then(data => {
if(data.status === 'success') {
location.reload(); // 刷新显示新评论
}
});
});
</script>
安全考虑
- 使用预处理语句防止SQL注入
- 对用户输入使用htmlspecialchars()进行转义
- 实现CSRF保护
- 对评论内容进行长度限制和敏感词过滤
性能优化
- 为video_id和created_at字段添加索引
- 实现评论分页功能
- 考虑使用缓存机制存储热门视频的评论
扩展功能
- 实现评论回复功能
- 添加点赞/反对功能
- 实现富文本编辑器支持
- 添加图片/表情支持
以上方法提供了视频评论系统的基本实现框架,可根据具体需求进行扩展和调整。







