DedeCMS(织梦内容管理系统)是一款基于PHP+MySQL架构的网站内容管理系统。点赞功能是指用户可以对某个内容(如文章、评论等)进行点赞操作,以表达对该内容的喜爱或支持。
CREATE TABLE `likes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`content_id` int(11) NOT NULL,
`created_at` datetime NOT NULL,
PRIMARY KEY (`id`)
);
<button id="like-btn" data-content-id="123">点赞</button>
<span id="like-count">0</span>
<script>
document.getElementById('like-btn').addEventListener('click', function() {
var contentId = this.getAttribute('data-content-id');
fetch('/api/like', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ content_id: contentId })
})
.then(response => response.json())
.then(data => {
document.getElementById('like-count').innerText = data.like_count;
});
});
</script>
<?php
// 假设使用PDO连接数据库
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 处理点赞请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content_id'])) {
$contentId = $_POST['content_id'];
$userId = 1; // 假设当前用户ID为1
// 检查是否已经点赞
$stmt = $db->prepare("SELECT COUNT(*) FROM likes WHERE user_id = ? AND content_id = ?");
$stmt->execute([$userId, $contentId]);
$hasLiked = $stmt->fetchColumn() > 0;
if (!$hasLiked) {
// 插入点赞记录
$stmt = $db->prepare("INSERT INTO likes (user_id, content_id, created_at) VALUES (?, ?, NOW())");
$stmt->execute([$userId, $contentId]);
// 更新点赞数
$stmt = $db->prepare("UPDATE contents SET like_count = like_count + 1 WHERE id = ?");
$stmt->execute([$contentId]);
}
// 获取当前点赞数
$stmt = $db->prepare("SELECT like_count FROM contents WHERE id = ?");
$stmt->execute([$contentId]);
$likeCount = $stmt->fetchColumn();
echo json_encode(['like_count' => $likeCount]);
}
?>
希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云