php实现收藏
PHP实现收藏功能
数据库设计
创建收藏表需要包含用户ID和内容ID,确保用户只能收藏一次同一内容。示例SQL语句:
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),
UNIQUE KEY unique_favorite (user_id, content_id)
);
添加收藏
处理用户请求添加收藏的逻辑,检查是否已收藏:
function addFavorite($userId, $contentId) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
// 检查是否已收藏
$stmt = $pdo->prepare("SELECT id FROM favorites WHERE user_id = ? AND content_id = ?");
$stmt->execute([$userId, $contentId]);
if ($stmt->fetch()) {
return ['status' => 'error', 'message' => 'Already favorited'];
}
// 添加收藏
$stmt = $pdo->prepare("INSERT INTO favorites (user_id, content_id) VALUES (?, ?)");
$stmt->execute([$userId, $contentId]);
return ['status' => 'success', 'message' => 'Added to favorites'];
}
移除收藏
提供移除收藏的功能:

function removeFavorite($userId, $contentId) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("DELETE FROM favorites WHERE user_id = ? AND content_id = ?");
$stmt->execute([$userId, $contentId]);
return ['status' => 'success', 'message' => 'Removed from favorites'];
}
获取用户收藏列表
查询用户的所有收藏内容:
function getUserFavorites($userId) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("
SELECT c.*
FROM contents c
JOIN favorites f ON c.id = f.content_id
WHERE f.user_id = ?
");
$stmt->execute([$userId]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
前端交互
使用AJAX实现无刷新收藏操作:

$('.favorite-btn').click(function() {
const contentId = $(this).data('content-id');
$.post('/favorite.php', { action: 'toggle', content_id: contentId }, function(response) {
if (response.status === 'added') {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
安全性考虑
实施CSRF保护并验证用户权限:
session_start();
function verifyUser($userId) {
return $_SESSION['user_id'] == $userId;
}
// 在所有收藏操作函数开头添加验证
if (!verifyUser($userId)) {
header('HTTP/1.1 403 Forbidden');
exit;
}
性能优化
为频繁查询的收藏数据添加缓存:
function getCachedFavorites($userId) {
$cacheKey = "user_favorites_{$userId}";
if ($cached = apc_fetch($cacheKey)) {
return $cached;
}
$favorites = getUserFavorites($userId);
apc_store($cacheKey, $favorites, 3600); // 缓存1小时
return $favorites;
}






