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 (user_id, post_id)
);
user_id和post_id组合唯一约束防止重复点赞。
后端PHP处理
创建点赞接口处理请求:
<?php
header('Content-Type: application/json');
// 假设已连接数据库
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$userId = $_POST['user_id'] ?? 0;
$postId = $_POST['post_id'] ?? 0;
// 验证输入
if (!$userId || !$postId) {
echo json_encode(['success' => false, 'message' => 'Invalid input']);
exit;
}
try {
// 检查是否已点赞
$stmt = $pdo->prepare("SELECT id FROM likes WHERE user_id = ? AND post_id = ?");
$stmt->execute([$userId, $postId]);
if ($stmt->fetch()) {
// 已点赞,执行取消
$pdo->prepare("DELETE FROM likes WHERE user_id = ? AND post_id = ?")->execute([$userId, $postId]);
echo json_encode(['success' => true, 'action' => 'unlike']);
} else {
// 未点赞,执行点赞
$pdo->prepare("INSERT INTO likes (user_id, post_id) VALUES (?, ?)")->execute([$userId, $postId]);
echo json_encode(['success' => true, 'action' => 'like']);
}
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
前端实现
使用AJAX发送点赞请求:
function toggleLike(postId, 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 button = document.querySelector(`.like-btn[data-post="${postId}"]`);
if (data.action === 'like') {
button.classList.add('liked');
button.textContent = 'Unlike';
} else {
button.classList.remove('liked');
button.textContent = 'Like';
}
}
});
}
获取点赞数量
添加获取点赞数量的接口:
<?php
header('Content-Type: application/json');
$postId = $_GET['post_id'] ?? 0;
if (!$postId) {
echo json_encode(['success' => false]);
exit;
}
try {
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM likes WHERE post_id = ?");
$stmt->execute([$postId]);
$result = $stmt->fetch();
echo json_encode(['success' => true, 'count' => $result['count']]);
} catch (PDOException $e) {
echo json_encode(['success' => false]);
}
性能优化考虑
对于高流量场景,可以考虑以下优化:

- 使用Redis等缓存系统存储点赞数据
- 批量更新数据库而非每次操作都写入
- 实现乐观锁防止并发问题
安全注意事项
- 验证用户身份防止伪造请求
- 对输入参数进行严格过滤
- 使用CSRF令牌保护表单
- 限制频繁操作防止滥用
以上实现提供了点赞功能的基本框架,可根据具体需求进行调整和扩展。






