php收藏实现
实现 PHP 收藏功能
PHP 实现收藏功能通常涉及数据库操作和用户交互逻辑。以下是实现收藏功能的常见方法和步骤:
数据库设计 创建收藏表需要包含用户ID和内容ID字段,例如:
CREATE TABLE favorites (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
content_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (content_id) REFERENCES contents(id)
);
添加收藏功能
// 检查用户是否登录
session_start();
if (!isset($_SESSION['user_id'])) {
die('请先登录');
}
// 获取参数
$content_id = $_POST['content_id'];
$user_id = $_SESSION['user_id'];
// 检查是否已收藏
$stmt = $pdo->prepare("SELECT id FROM favorites WHERE user_id = ? AND content_id = ?");
$stmt->execute([$user_id, $content_id]);
if ($stmt->rowCount() > 0) {
echo '已收藏';
} else {
// 添加收藏
$insert = $pdo->prepare("INSERT INTO favorites (user_id, content_id) VALUES (?, ?)");
$insert->execute([$user_id, $content_id]);
echo '收藏成功';
}
取消收藏功能

$delete = $pdo->prepare("DELETE FROM favorites WHERE user_id = ? AND content_id = ?");
$delete->execute([$user_id, $content_id]);
echo '已取消收藏';
获取用户收藏列表
$stmt = $pdo->prepare("SELECT c.* FROM contents c
JOIN favorites f ON c.id = f.content_id
WHERE f.user_id = ?");
$stmt->execute([$user_id]);
$favorites = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 输出收藏列表
foreach ($favorites as $item) {
echo $item['title']."<br>";
}
前端交互实现 HTML部分可以这样设计:
<button class="favorite-btn" data-content-id="123">收藏</button>
JavaScript部分:

$('.favorite-btn').click(function() {
const contentId = $(this).data('content-id');
$.post('/favorite.php', {content_id: contentId}, function(response) {
alert(response);
});
});
安全性考虑
- 使用预处理语句防止SQL注入
- 验证用户登录状态
- 对输入参数进行过滤和验证
- 实现CSRF防护
性能优化
- 为常用查询字段添加索引
- 考虑缓存热门收藏内容
- 分页显示收藏列表
扩展功能
- 收藏分类管理
- 批量操作功能
- 收藏导出功能
- 收藏提醒功能
以上实现可以根据具体项目需求进行调整和扩展,核心思路是通过数据库记录用户与内容的关联关系,并提供相应的增删查改接口。






