php 收藏功能实现
数据库设计
需要创建两张表:articles(文章表)和favorites(收藏表)。articles表存储文章信息,favorites表记录用户收藏行为。
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL
);
CREATE TABLE favorites (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
article_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (article_id) REFERENCES articles(id)
);
收藏功能实现
在PHP中实现收藏功能需要处理用户请求,检查是否已收藏,然后执行相应操作。

// 连接数据库
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
// 处理收藏请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['article_id'], $_POST['user_id'])) {
$articleId = $_POST['article_id'];
$userId = $_POST['user_id'];
// 检查是否已收藏
$stmt = $pdo->prepare("SELECT id FROM favorites WHERE user_id = ? AND article_id = ?");
$stmt->execute([$userId, $articleId]);
$isFavorited = $stmt->fetch();
if ($isFavorited) {
// 取消收藏
$stmt = $pdo->prepare("DELETE FROM favorites WHERE user_id = ? AND article_id = ?");
$stmt->execute([$userId, $articleId]);
echo json_encode(['status' => 'unfavorited']);
} else {
// 添加收藏
$stmt = $pdo->prepare("INSERT INTO favorites (user_id, article_id) VALUES (?, ?)");
$stmt->execute([$userId, $articleId]);
echo json_encode(['status' => 'favorited']);
}
exit;
}
前端交互
使用AJAX实现无刷新收藏功能,提升用户体验。
<button id="favorite-btn" data-article-id="1" data-user-id="1">收藏</button>
<script>
document.getElementById('favorite-btn').addEventListener('click', function() {
const articleId = this.getAttribute('data-article-id');
const userId = this.getAttribute('data-user-id');
fetch('favorite.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `article_id=${articleId}&user_id=${userId}`
})
.then(response => response.json())
.then(data => {
if (data.status === 'favorited') {
this.textContent = '已收藏';
} else {
this.textContent = '收藏';
}
});
});
</script>
显示收藏状态
页面加载时检查当前用户是否已收藏该文章。

// 检查收藏状态
$stmt = $pdo->prepare("SELECT id FROM favorites WHERE user_id = ? AND article_id = ?");
$stmt->execute([$userId, $articleId]);
$isFavorited = $stmt->fetch();
// 输出按钮HTML
echo '<button id="favorite-btn" data-article-id="'.$articleId.'" data-user-id="'.$userId.'">';
echo $isFavorited ? '已收藏' : '收藏';
echo '</button>';
安全性考虑
实现收藏功能时需要注意防止SQL注入和CSRF攻击。
// 使用预处理语句防止SQL注入
$stmt = $pdo->prepare("INSERT INTO favorites (user_id, article_id) VALUES (?, ?)");
$stmt->execute([$userId, $articleId]);
// 添加CSRF令牌验证
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token validation failed');
}
}
性能优化
对于大量收藏数据,可以考虑添加索引和缓存。
-- 为favorites表添加复合索引
CREATE INDEX idx_user_article ON favorites(user_id, article_id);
-- 使用Redis缓存热门文章的收藏数
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->incr("article:$articleId:favorites");






