Like button

Programming Language : programming_language : MySQL

Mayank Kolwal

Email

1000089505.png

Like button insert your website

0
HTML Code
<div class="cd-like-box" data-post-id="1">

    <button class="cd-like-button" type="button">

        <span class="cd-heart">♡</span>

        <span class="cd-like-text">
            Like
        </span>

        <span class="cd-like-count">
            0
        </span>

    </button>

</div>
CSS Code
.cd-like-box {
    display: inline-block;
    font-family: Arial, sans-serif;
}

.cd-like-button {
    display: flex;
    align-items: center;
    gap: 8px;

    padding: 9px 14px;

    background: #ffffff;
    color: #e53935;

    border: 1px solid #e53935;
    border-radius: 8px;

    font-size: 16px;
    font-weight: 600;

    cursor: pointer;

    transition: 0.2s ease;
}

.cd-like-button:hover {
    background: #fff5f5;
}

.cd-heart {
    font-size: 25px;
    line-height: 1;
}

.cd-like-count {
    padding: 3px 8px;

    background: #fff1f1;

    border-radius: 6px;

    font-size: 14px;
}

.cd-like-button.cd-liked {
    background: #e53935;
    color: #ffffff;
}

.cd-like-button.cd-liked .cd-like-count {
    background: rgba(255,255,255,0.2);
}
JavaScript Code
<script>
document.querySelectorAll(".cd-like-box").forEach(function(box) {

    const button = box.querySelector(".cd-like-button");
    const heart = box.querySelector(".cd-heart");
    const text = box.querySelector(".cd-like-text");
    const count = box.querySelector(".cd-like-count");

    button.addEventListener("click", function() {

        const postId = box.dataset.postId;

        button.disabled = true;

        const formData = new FormData();

        formData.append("post_id", postId);

        fetch("like.php", {
            method: "POST",
            body: formData
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {

            if (data.success) {

                count.textContent = data.total_likes;

                if (data.status === "liked") {

                    button.classList.add("cd-liked");

                    heart.textContent = "♥";
                    text.textContent = "Liked";

                } else {

                    button.classList.remove("cd-liked");

                    heart.textContent = "♡";
                    text.textContent = "Like";
                }
            }

        })
        .catch(function(error) {

            console.error("Like error:", error);

        })
        .finally(function() {

            button.disabled = false;

        });

    });

});
</script>
PHP Code
config.php
<?php

$host = "localhost";
$user = "YOUR_DATABASE_USER";
$password = "YOUR_DATABASE_PASSWORD";
$database = "YOUR_DATABASE_NAME";

$conn = new mysqli(
    $host,
    $user,
    $password,
    $database
);

if ($conn->connect_error) {
    http_response_code(500);
    die("Database connection failed.");
}

$conn->set_charset("utf8mb4");
?>
like.php
<?php

header("Content-Type: application/json");

require_once "config.php";

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode([
        "success" => false,
        "message" => "Invalid request"
    ]);
    exit;
}

$post_id = isset($_POST["post_id"])
    ? intval($_POST["post_id"])
    : 0;

if ($post_id <= 0) {
    echo json_encode([
        "success" => false,
        "message" => "Invalid post ID"
    ]);
    exit;
}

$ip_address = $_SERVER["REMOTE_ADDR"] ?? "unknown";

/*
 * Check whether this person/IP
 * already liked this post.
 */

$check = $conn->prepare(
    "SELECT id FROM likes
     WHERE post_id = ? AND ip_address = ?
     LIMIT 1"
);

$check->bind_param(
    "is",
    $post_id,
    $ip_address
);

$check->execute();

$result = $check->get_result();

if ($result->num_rows > 0) {

    /*
     * Already liked.
     * Remove the like.
     */

    $delete = $conn->prepare(
        "DELETE FROM likes
         WHERE post_id = ? AND ip_address = ?"
    );

    $delete->bind_param(
        "is",
        $post_id,
        $ip_address
    );

    $delete->execute();

    $status = "unliked";

} else {

    /*
     * New like.
     */

    $insert = $conn->prepare(
        "INSERT INTO likes
        (post_id, ip_address)
        VALUES (?, ?)"
    );

    $insert->bind_param(
        "is",
        $post_id,
        $ip_address
    );

    $insert->execute();

    $status = "liked";
}


/*
 * Get the NEW total count.
 */

$count = $conn->prepare(
    "SELECT COUNT(*) AS total
     FROM likes
     WHERE post_id = ?"
);

$count->bind_param(
    "i",
    $post_id
);

$count->execute();

$count_result = $count->get_result();

$row = $count_result->fetch_assoc();

$total_likes = intval($row["total"]);


echo json_encode([
    "success" => true,
    "status" => $status,
    "total_likes" => $total_likes
]);

$conn->close();

?>
MySQL Code
CREATE TABLE likes (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id INT UNSIGNED NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY unique_like (post_id, ip_address)
);
UNIQUE KEY unique_like (post_id, ip_address)

Leave a Comment