Facebook’s “Like” reactions feature allows users to express their feelings toward content with a range of reactions beyond just a simple like. Implementing a similar feature in your web application can enhance user engagement and interaction. In this guide, we’ll walk you through how to create a Facebook-like reactions system using PHP, MySQL, and jQuery.
Prerequisites
Before diving into the implementation, ensure you have:
- Basic knowledge of PHP, MySQL, and jQuery.
- A working web server environment with PHP and MySQL installed.
- Access to a MySQL database.
Step 1: Set Up Your MySQL Database
First, create a MySQL database and table to store the reactions. Open your MySQL client and run the following SQL queries:
CREATE DATABASE reactions_db;
USE reactions_db;
CREATE TABLE reactions (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT NOT NULL,
reaction_type VARCHAR(50) NOT NULL,
UNIQUE KEY unique_reaction (post_id, user_id)
);
Explanation
- Database Creation:
reactions_db
is the name of the database where reaction data will be stored. - Table Structure: The
reactions
table stores thepost_id
,user_id
, andreaction_type
(like, love, haha, etc.). Theunique_reaction
key ensures that each user can only react once per post.
Step 2: Create Your PHP Backend
Create a PHP file named reactions.php
to handle inserting and retrieving reactions. This script will interact with the MySQL database to store and fetch reaction data.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "reactions_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post_id = $_POST['post_id'];
$user_id = $_POST['user_id'];
$reaction_type = $_POST['reaction_type'];
// Insert or update reaction
$sql = "INSERT INTO reactions (post_id, user_id, reaction_type)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE reaction_type = VALUES(reaction_type)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iis", $post_id, $user_id, $reaction_type);
$stmt->execute();
$stmt->close();
echo json_encode(['success' => true]);
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
$post_id = $_GET['post_id'];
// Retrieve reactions
$sql = "SELECT reaction_type, COUNT(*) AS count FROM reactions
WHERE post_id = ?
GROUP BY reaction_type";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $post_id);
$stmt->execute();
$result = $stmt->get_result();
$reactions = [];
while ($row = $result->fetch_assoc()) {
$reactions[$row['reaction_type']] = $row['count'];
}
echo json_encode($reactions);
$stmt->close();
}
$conn->close();
?>
Explanation
- Connection: The PHP script establishes a connection to the MySQL database.
- POST Request: Handles inserting or updating reactions based on
post_id
,user_id
, andreaction_type
. - GET Request: Retrieves and aggregates reaction counts by
reaction_type
for a givenpost_id
.
Step 3: Create the Frontend with HTML, jQuery, and CSS
Create an HTML file named index.html
to display the reactions and handle user interactions with jQuery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook Like Reactions</title>
<style>
.reaction-button {
margin: 5px;
padding: 10px;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 5px;
}
.reaction-count {
display: inline-block;
margin-left: 10px;
}
</style>
</head>
<body>
<h1>Facebook Like Reactions</h1>
<div id="post-reactions">
<div class="reaction-button" data-reaction="like">Like <span class="reaction-count" id="like-count">0</span></div>
<div class="reaction-button" data-reaction="love">Love <span class="reaction-count" id="love-count">0</span></div>
<div class="reaction-button" data-reaction="haha">Haha <span class="reaction-count" id="haha-count">0</span></div>
<!-- Add more reactions as needed -->
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const postId = 1; // Replace with dynamic post ID if needed
const userId = 1; // Replace with dynamic user ID if needed
$(document).ready(function() {
loadReactions();
$('.reaction-button').click(function() {
const reactionType = $(this).data('reaction');
$.post('reactions.php', { post_id: postId, user_id: userId, reaction_type: reactionType }, function(response) {
if (response.success) {
loadReactions();
}
}, 'json');
});
function loadReactions() {
$.get('reactions.php', { post_id: postId }, function(data) {
for (const [reaction, count] of Object.entries(data)) {
$(`#${reaction}-count`).text(count);
}
}, 'json');
}
});
</script>
</body>
</html>
Explanation
- HTML Structure: The HTML file creates a basic layout with reaction buttons and counts.
- jQuery: Handles button clicks and sends AJAX requests to the PHP backend to update and retrieve reactions.
- CSS: Adds basic styling to the reaction buttons.
Conclusion
Implementing a Facebook-like reactions system using PHP, MySQL, and jQuery can greatly enhance user interaction on your web application. By setting up a MySQL database to store reactions, creating a PHP backend to handle data operations, and using jQuery for dynamic updates, you can provide a robust and engaging experience similar to popular social media platforms. Customize the reactions and styling according to your applicationās needs to create a seamless and interactive user experience.