要在PHP中实现点赞功能,您需要以下几个步骤:
likes
的表,包含字段id
(自动递增的主键)、user_id
(点赞用户的ID)和post_id
(被点赞内容的ID)。CREATE TABLE likes (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
post_id INT NOT NULL,
UNIQUE (user_id, post_id)
);
<span class="like-count"><?php echo $like_count; ?></span>
$(".like-btn").on("click", function() {
var postId = $(this).data("post-id");
$.ajax({
url: "like.php",
type: "POST",
data: {post_id: postId},
success: function(response) {
if (response.success) {
// 更新点赞计数
$(".like-count").text(response.like_count);
} else {
alert("点赞失败,请重试。");
}
},
error: function() {
alert("服务器错误,请稍后重试。");
}
});
});
like.php
文件)处理AJAX请求,将点赞信息插入到数据库,并返回更新后的点赞数量。<?php
session_start();
// 连接数据库
$db = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
// 获取请求参数
$postId = $_POST["post_id"];
$userId = isset($_SESSION["user_id"]) ? $_SESSION["user_id"] : null;
if ($userId) {
try {
// 插入点赞记录
$stmt = $db->prepare("INSERT INTO likes (user_id, post_id) VALUES (:user_id, :post_id)");
$stmt->execute([":user_id" => $userId, ":post_id" => $postId]);
// 查询点赞数量
$stmt = $db->prepare("SELECT COUNT(*) as like_count FROM likes WHERE post_id = :post_id");
$stmt->execute([":post_id" => $postId]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode(["success" => true, "like_count" => $result["like_count"]]);
} catch (PDOException $e) {
echo json_encode(["success" => false]);
}
} else {
echo json_encode(["success" => false]);
}
?>
这样就实现了一个基本的点赞功能。注意,这里没有对用户进行身份验证,实际项目中需要确保用户已登录才能点赞。此外,还可以根据需求添加取消点赞等功能。