php实现点赞
PHP实现点赞功能
点赞功能通常涉及前端交互和后端数据存储。以下是实现点赞功能的详细步骤:
数据库设计 创建存储点赞数据的表结构:
CREATE TABLE likes (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
post_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY unique_like (user_id, post_id)
);
后端处理 创建处理点赞的PHP脚本(like.php):

<?php
header('Content-Type: application/json');
require 'db_connection.php';
$userId = $_POST['user_id'] ?? null;
$postId = $_POST['post_id'] ?? null;
if (!$userId || !$postId) {
echo json_encode(['success' => false, 'message' => 'Missing parameters']);
exit;
}
try {
$pdo->beginTransaction();
// 检查是否已点赞
$stmt = $pdo->prepare("SELECT id FROM likes WHERE user_id = ? AND post_id = ?");
$stmt->execute([$userId, $postId]);
if ($stmt->rowCount() > 0) {
// 取消点赞
$pdo->prepare("DELETE FROM likes WHERE user_id = ? AND post_id = ?")->execute([$userId, $postId]);
$action = 'unlike';
} else {
// 添加点赞
$pdo->prepare("INSERT INTO likes (user_id, post_id) VALUES (?, ?)")->execute([$userId, $postId]);
$action = 'like';
}
// 获取最新点赞数
$count = $pdo->query("SELECT COUNT(*) FROM likes WHERE post_id = $postId")->fetchColumn();
$pdo->commit();
echo json_encode(['success' => true, 'action' => $action, 'count' => $count]);
} catch (Exception $e) {
$pdo->rollBack();
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
前端实现 使用AJAX实现无刷新点赞:
document.querySelectorAll('.like-btn').forEach(btn => {
btn.addEventListener('click', function() {
const postId = this.dataset.postId;
const userId = this.dataset.userId; // 实际应用中应从会话获取
fetch('like.php', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `user_id=${userId}&post_id=${postId}`
})
.then(response => response.json())
.then(data => {
if (data.success) {
const counter = document.querySelector(`.like-count[data-post-id="${postId}"]`);
counter.textContent = data.count;
this.classList.toggle('liked', data.action === 'like');
}
});
});
});
安全考虑

- 使用预处理语句防止SQL注入
- 验证用户身份(实际应用中应使用会话或Token验证)
- 添加CSRF保护
- 对频繁请求进行限流
性能优化
- 使用Redis缓存热门内容的点赞数
- 批量更新避免频繁数据库操作
- 考虑使用消息队列处理高并发场景
扩展功能
- 添加点赞通知系统
- 实现点赞排行榜
- 增加点赞动画效果
- 支持取消点赞功能
以上实现可根据具体需求进行调整,例如添加更多字段记录点赞时间或类型。对于大型应用,建议使用专门的计数服务来处理高频率的点赞操作。






