How to develop Projects(BlogApp) Using PHP and Mysql Part 11

Rashmi Mishra
0

How to develop Projects(BlogApp)

 Using PHP and Mysql 

Part 11

 

 Module 3: 👍 Like / 👎 Dislike Feature

🎯 Purpose:
Enable users to react to blog posts with likes or dislikes, increasing engagement and feedback.


Functionalities:

  •  Like a blog post
  •  Dislike a blog post
  •  Toggle between like and dislike
  •  View like/dislike count on each post

Project Structure:

│── /reactions/

   ── like_dislike.php         # Handle like/dislike requests

   ── reaction_count.php       # Get like/dislike count for blog


Database Table:

CREATE TABLE reactions (

    id INT AUTO_INCREMENT PRIMARY KEY,

    blog_id INT NOT NULL,

    user_id INT NOT NULL,

    reaction ENUM('like', 'dislike') NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    UNIQUE(blog_id, user_id),  -- one reaction per user per blog

    FOREIGN KEY (blog_id) REFERENCES blogs(id) ON DELETE CASCADE,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

);

💾 Database Table:

First, your table setup looks great. Here it is again for clarity:

CREATE TABLE reactions (

    id INT AUTO_INCREMENT PRIMARY KEY,

    blog_id INT NOT NULL,

    user_id INT NOT NULL,

    reaction ENUM('like', 'dislike') NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    UNIQUE(blog_id, user_id),

    FOREIGN KEY (blog_id) REFERENCES blogs(id) ON DELETE CASCADE,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

);


💻 like_dislike.php

This handles both LIKE and DISLIKE actions.

<?php

session_start();

$conn = new mysqli("localhost", "root", "", "blog_db");

 

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

 

$user_id = $_SESSION['user_id']; // Assuming user login is required

$blog_id = $_POST['blog_id'];

$reaction = $_POST['reaction']; // 'like' or 'dislike'

 

if (!in_array($reaction, ['like', 'dislike'])) {

    echo "Invalid reaction!";

    exit;

}

 

// Check if reaction exists

$sql = "SELECT * FROM reactions WHERE blog_id = ? AND user_id = ?";

$stmt = $conn->prepare($sql);

$stmt->bind_param("ii", $blog_id, $user_id);

$stmt->execute();

$result = $stmt->get_result();

 

if ($result->num_rows > 0) {

    // Update reaction

    $update = $conn->prepare("UPDATE reactions SET reaction = ?, created_at = NOW() WHERE blog_id = ? AND user_id = ?");

    $update->bind_param("sii", $reaction, $blog_id, $user_id);

    $update->execute();

    echo "Reaction Updated!";

} else {

    // Insert new reaction

    $insert = $conn->prepare("INSERT INTO reactions (blog_id, user_id, reaction) VALUES (?, ?, ?)");

    $insert->bind_param("iis", $blog_id, $user_id, $reaction);

    $insert->execute();

    echo "Reaction Added!";

}

?>


💻 reaction_count.php

This shows the total likes and dislikes for a blog post.

<?php

$conn = new mysqli("localhost", "root", "", "blog_db");

 

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

 

$blog_id = $_GET['blog_id'];

 

$sql = "SELECT reaction, COUNT(*) as total FROM reactions WHERE blog_id = ? GROUP BY reaction";

$stmt = $conn->prepare($sql);

$stmt->bind_param("i", $blog_id);

$stmt->execute();

$result = $stmt->get_result();

 

$counts = ['like' => 0, 'dislike' => 0];

while ($row = $result->fetch_assoc()) {

    $counts[$row['reaction']] = $row['total'];

}

 

echo json_encode($counts);

?>


🌐 Example Usage with AJAX:

If you want to add a button interface for like/dislike using JavaScript:

<button onclick="react(1, 'like')">👍 Like</button>

<button onclick="react(1, 'dislike')">👎 Dislike</button>

 

<div id="count"></div>

 

<script>

function react(blog_id, reaction) {

    fetch('reactions/like_dislike.php', {

        method: 'POST',

        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

        body: 'blog_id=' + blog_id + '&reaction=' + reaction

    })

    .then(res => res.text())

    .then(alertAndUpdate);

}

 

function alertAndUpdate(response) {

    alert(response);

    fetch('reactions/reaction_count.php?blog_id=1')

    .then(res => res.json())

    .then(data => {

        document.getElementById('count').innerHTML =

            `👍 Likes: ${data.like} | 👎 Dislikes: ${data.dislike}`;

    });

}

</script>


 


Post a Comment

0Comments

Post a Comment (0)