php实现收藏功能实现
实现收藏功能的基本思路
收藏功能通常涉及用户与内容的交互,需要数据库存储用户ID和收藏内容的ID。核心逻辑包括添加收藏、取消收藏、检查是否已收藏以及展示收藏列表。
数据库设计
创建收藏表(favorites)的基本结构:
CREATE TABLE favorites (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
item_id INT NOT NULL,
item_type VARCHAR(50) NOT NULL, -- 如'article','product'等
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY user_item_unique (user_id, item_id, item_type)
);
添加收藏
通过PHP处理前端AJAX请求,插入收藏记录:
// add_favorite.php
$userId = $_SESSION['user_id'];
$itemId = $_POST['item_id'];
$itemType = $_POST['item_type'];
// 检查是否已收藏
$checkSql = "SELECT id FROM favorites WHERE user_id = ? AND item_id = ? AND item_type = ?";
$stmt = $pdo->prepare($checkSql);
$stmt->execute([$userId, $itemId, $itemType]);
if ($stmt->rowCount() > 0) {
echo json_encode(['status' => 'error', 'message' => '已收藏']);
exit;
}
// 添加收藏
$insertSql = "INSERT INTO favorites (user_id, item_id, item_type) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($insertSql);
$stmt->execute([$userId, $itemId, $itemType]);
echo json_encode(['status' => 'success']);
取消收藏
删除对应的收藏记录:
// remove_favorite.php
$userId = $_SESSION['user_id'];
$itemId = $_POST['item_id'];
$itemType = $_POST['item_type'];
$deleteSql = "DELETE FROM favorites WHERE user_id = ? AND item_id = ? AND item_type = ?";
$stmt = $pdo->prepare($deleteSql);
$stmt->execute([$userId, $itemId, $itemType]);
echo json_encode(['status' => 'success']);
检查收藏状态
判断用户是否已收藏某内容:
function isFavorited($userId, $itemId, $itemType) {
global $pdo;
$sql = "SELECT id FROM favorites WHERE user_id = ? AND item_id = ? AND item_type = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId, $itemId, $itemType]);
return $stmt->rowCount() > 0;
}
获取收藏列表
查询用户的所有收藏项:
function getUserFavorites($userId, $itemType = null) {
global $pdo;
$sql = "SELECT * FROM favorites WHERE user_id = ?";
$params = [$userId];
if ($itemType) {
$sql .= " AND item_type = ?";
$params[] = $itemType;
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
前端交互示例
使用jQuery处理收藏按钮点击:
$('.favorite-btn').click(function() {
const itemId = $(this).data('item-id');
const itemType = $(this).data('item-type');
const isFavorited = $(this).hasClass('active');
$.post(isFavorited ? 'remove_favorite.php' : 'add_favorite.php', {
item_id: itemId,
item_type: itemType
}, function(response) {
if (response.status === 'success') {
$(this).toggleClass('active');
}
}.bind(this));
});
性能优化建议
对于高频访问的收藏状态检查,可以考虑使用Redis缓存用户收藏状态。建立用户ID为key,收藏项ID集合为value的缓存结构,减少数据库查询压力。

定期清理长时间未访问的缓存数据,保持缓存效率。对于收藏列表分页查询,确保SQL语句使用正确的索引以提高查询速度。






