php 实现收藏功能
实现收藏功能的基本思路
收藏功能通常涉及用户与内容的交互,需要数据库存储用户ID和内容ID的关联关系。以下是PHP实现收藏功能的常见方法。
数据库设计
创建收藏表favorites,包含用户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,
UNIQUE KEY unique_favorite (user_id, content_id)
);
收藏功能实现
建立数据库连接文件db_connect.php:
<?php
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
添加收藏功能
创建add_favorite.php处理收藏请求:
<?php
require 'db_connect.php';
session_start();
if (!isset($_SESSION['user_id'])) {
die('User not logged in');
}
$userId = $_SESSION['user_id'];
$contentId = $_POST['content_id'];
try {
$stmt = $pdo->prepare("INSERT INTO favorites (user_id, content_id) VALUES (?, ?)");
$stmt->execute([$userId, $contentId]);
echo 'Added to favorites';
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) {
echo 'Already in favorites';
} else {
echo 'Error: ' . $e->getMessage();
}
}
?>
移除收藏功能
创建remove_favorite.php处理取消收藏:
<?php
require 'db_connect.php';
session_start();
if (!isset($_SESSION['user_id'])) {
die('User not logged in');
}
$userId = $_SESSION['user_id'];
$contentId = $_POST['content_id'];
try {
$stmt = $pdo->prepare("DELETE FROM favorites WHERE user_id = ? AND content_id = ?");
$stmt->execute([$userId, $contentId]);
echo $stmt->rowCount() > 0 ? 'Removed from favorites' : 'Not in favorites';
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
检查收藏状态
创建check_favorite.php检查收藏状态:
<?php
require 'db_connect.php';
session_start();
if (!isset($_SESSION['user_id'])) {
die('User not logged in');
}
$userId = $_SESSION['user_id'];
$contentId = $_GET['content_id'];
$stmt = $pdo->prepare("SELECT COUNT(*) FROM favorites WHERE user_id = ? AND content_id = ?");
$stmt->execute([$userId, $contentId]);
$isFavorite = $stmt->fetchColumn() > 0;
echo json_encode(['is_favorite' => $isFavorite]);
?>
前端交互实现
HTML和JavaScript示例:
<button id="favorite-btn" data-content-id="123">Add to Favorites</button>
<script>
document.getElementById('favorite-btn').addEventListener('click', function() {
const contentId = this.getAttribute('data-content-id');
const isFavorite = this.textContent.includes('Remove');
fetch(isFavorite ? 'remove_favorite.php' : 'add_favorite.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `content_id=${contentId}`
})
.then(response => response.text())
.then(result => {
this.textContent = isFavorite ? 'Add to Favorites' : 'Remove from Favorites';
});
});
</script>
获取用户收藏列表
创建get_favorites.php获取用户收藏:
<?php
require 'db_connect.php';
session_start();
if (!isset($_SESSION['user_id'])) {
die('User not logged in');
}
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT content_id FROM favorites WHERE user_id = ?");
$stmt->execute([$userId]);
$favorites = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($favorites);
?>
安全注意事项
验证用户输入防止SQL注入:
$contentId = filter_input(INPUT_POST, 'content_id', FILTER_VALIDATE_INT);
if (!$contentId) {
die('Invalid content ID');
}
实现收藏功能时,确保用户认证和输入验证到位,防止未授权访问和数据篡改。






