要在PHP中實(shí)現(xiàn)點(diǎn)贊功能,您需要以下幾個(gè)步驟:
likes
的表,包含字段id
(自動(dòng)遞增的主鍵)、user_id
(點(diǎn)贊用戶的ID)和post_id
(被點(diǎn)贊內(nèi)容的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) {
// 更新點(diǎn)贊計(jì)數(shù)
$(".like-count").text(response.like_count);
} else {
alert("點(diǎn)贊失敗,請(qǐng)重試。");
}
},
error: function() {
alert("服務(wù)器錯(cuò)誤,請(qǐng)稍后重試。");
}
});
});
like.php
文件)處理AJAX請(qǐng)求,將點(diǎn)贊信息插入到數(shù)據(jù)庫,并返回更新后的點(diǎn)贊數(shù)量。<?php
session_start();
// 連接數(shù)據(jù)庫
$db = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
// 獲取請(qǐng)求參數(shù)
$postId = $_POST["post_id"];
$userId = isset($_SESSION["user_id"]) ? $_SESSION["user_id"] : null;
if ($userId) {
try {
// 插入點(diǎn)贊記錄
$stmt = $db->prepare("INSERT INTO likes (user_id, post_id) VALUES (:user_id, :post_id)");
$stmt->execute([":user_id" => $userId, ":post_id" => $postId]);
// 查詢點(diǎn)贊數(shù)量
$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]);
}
?>
這樣就實(shí)現(xiàn)了一個(gè)基本的點(diǎn)贊功能。注意,這里沒有對(duì)用戶進(jìn)行身份驗(yàn)證,實(shí)際項(xiàng)目中需要確保用戶已登錄才能點(diǎn)贊。此外,還可以根據(jù)需求添加取消點(diǎn)贊等功能。