要在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]);
}
?>
這樣就實現了一個基本的點贊功能。注意,這里沒有對用戶進行身份驗證,實際項目中需要確保用戶已登錄才能點贊。此外,還可以根據需求添加取消點贊等功能。