php收藏实现
PHP 收藏功能实现方法
数据库设计
创建一个表来存储用户收藏数据,基本字段包括:
CREATE TABLE `user_favorites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`item_type` varchar(50) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `user_item` (`user_id`,`item_id`,`item_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
添加收藏功能
function addFavorite($userId, $itemId, $itemType) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO user_favorites (user_id, item_id, item_type) VALUES (?, ?, ?)");
return $stmt->execute([$userId, $itemId, $itemType]);
}
移除收藏功能
function removeFavorite($userId, $itemId, $itemType) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("DELETE FROM user_favorites WHERE user_id = ? AND item_id = ? AND item_type = ?");
return $stmt->execute([$userId, $itemId, $itemType]);
}
检查收藏状态
function isFavorite($userId, $itemId, $itemType) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("SELECT COUNT(*) FROM user_favorites WHERE user_id = ? AND item_id = ? AND item_type = ?");
$stmt->execute([$userId, $itemId, $itemType]);
return $stmt->fetchColumn() > 0;
}
获取用户收藏列表
function getUserFavorites($userId, $itemType = null) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$sql = "SELECT item_id, item_type FROM user_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);
}
前端交互实现
使用AJAX实现无刷新收藏操作:
$('.favorite-btn').click(function() {
const itemId = $(this).data('item-id');
const itemType = $(this).data('item-type');
$.post('/favorite_toggle.php', {
item_id: itemId,
item_type: itemType
}, function(response) {
if(response.status === 'added') {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
安全性考虑
实现收藏功能时需要注意:
- 验证用户登录状态
- 对输入参数进行过滤和验证
- 使用预处理语句防止SQL注入
- 限制单个用户的收藏数量
性能优化建议
对于大量收藏数据:
- 添加适当的索引
- 考虑分页加载收藏列表
- 实现缓存机制减少数据库查询







