Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 15, 2023 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/40876729712a53d68b025cacf1d7bf1b to your computer and use it in GitHub Desktop.
Save code-boxx/40876729712a53d68b025cacf1d7bf1b to your computer and use it in GitHub Desktop.
PHP MYSQL Like Dislike System

PHP MYSQL LIKE DISLIKE

https://code-boxx.com/php-like-dislike-system/

NOTES

  1. Create a database and import 1-database.sql.
  2. Change the database settings in 2-lidi-lib.php to your own.
  3. Launch 4-demo.php in your browser.

IMAGES

demo lidi

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) REACTIONS TABLE
CREATE TABLE `reactions` (
`id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`reaction` tinyint(1) NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `reactions`
ADD PRIMARY KEY (`id`,`user_id`),
ADD KEY `reaction` (`reaction`);
-- (B) DUMMY DATA
INSERT INTO `reactions` (`id`, `user_id`, `reaction`) VALUES
(900, 1, -1),
(900, 2, 1),
(900, 3, 1),
(900, 4, -1);
<?php
class Reactions {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo;
private $stmt;
public $error;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
$this->pdo = null;
$this->stmt = null;
}
// (C) HELPER FUNCTION - RUN SQL
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET REACTIONS FOR ID
function get ($id, $uid=null) {
// (D1) GET TOTAL REACTIONS
$reacts = ["react" => [0, 0]]; // [likes, dislikes]
$this->query(
"SELECT `reaction`, COUNT(`reaction`) `total`
FROM `reactions` WHERE `id`=?
GROUP BY `reaction`", [$id]
);
while ($r = $this->stmt->fetch()) {
if ($r["reaction"]==1) { $reacts["react"][0] = $r["total"]; }
else { $reacts["react"][1] = $r["total"]; }
}
// (D2) GET REACTION BY USER (IF SPECIFIED)
if ($uid != null) {
$this->query(
"SELECT `reaction` FROM `reactions` WHERE `id`=? AND `user_id`=?",
[$id, $uid]
);
$reacts["user"] = $this->stmt->fetchColumn();
}
// (D3) DONE - RETURN RESULTS
return $reacts;
}
// (E) SAVE REACTION
function save ($id, $uid, $react) {
// (E1) FORMULATE SQL
if ($react == 0) {
$sql = "DELETE FROM `reactions` WHERE `id`=? AND `user_id`=?";
$data = [$id, $uid];
} else {
$sql = "REPLACE INTO `reactions` (`id`, `user_id`, `reaction`) VALUES (?,?,?)";
$data = [$id, $uid, $react];
}
// (E2) EXECUTE SQL
$this->query($sql, $data);
return true;
}
}
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (G) NEW REACTIONS OBJECT
$_REACT = new Reactions();
<?php
if (isset($_POST["req"])) {
// (A) LOAD LIKE DISLIKE LIBRARY
require "2-lidi-lib.php";
// (B) FIXED DUMMY USER ID
$uid = 1;
// (C) HANDLE REQUESTS
switch ($_POST["req"]) {
// (C1) GET REACTIONS
case "get":
echo json_encode($_REACT->get($_POST["pid"], $uid));
break;
// (C2) SAVE REACTION
case "save":
if ($_REACT->save($_POST["pid"], $uid, $_POST["react"])) {
echo json_encode($_REACT->get($_POST["pid"], $uid));
} else { echo $_REACT->error ; }
break;
}}
var demo = {
// (A) SUPPORT FUNCTION - AJAX FETCH
fetch : (data, load) => {
// (A1) FORM DATA
var form = new FormData();
for (let [k,v] of Object.entries(data)) { form.append(k, v); }
// (A2) AJAX FETCH
fetch("3-lidi-ajax.php", { method: "post", body : form })
.then(res => res.json())
.then(res => load(res))
.catch(err => console.error(err));
},
// (B) INIT
lidi : null, // like dislike instance
init : () => demo.fetch(
// (B1) GET LIKES COUNT FROM SERVER
{
req : "get",
pid : 900 // fixed dummy product id
},
// (B2) DRAW HTML LIKE/DISLIKE BUTTON
data => {
demo.lidi = lidi({
hWrap : document.getElementById("demo"),
status : data.user ? data.user : 0,
count : data.react,
change : demo.save
});
}
),
// (C) SAVE LIKE/DISLIKE REACTION
save : status => demo.fetch(
// (C1) SEND NEW STATUS TO SERVER
{
req : "save",
react : status,
pid : 900 // fixed dummy product id
},
// (C2) UPDATE HTML COUNT
res => demo.lidi.recount(res.react)
)
};
window.onload = demo.init;
<!DOCTYPE html>
<html>
<head>
<title>PHP MYSQL Like Dislike</title>
<meta charset="utf-8">
<!-- (X) NOT IMPORTANT -->
<style>
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
#demowrap {
width: 300px; padding: 15px;
background: #b31212;
display: flex; flex-direction: column; align-items: center;
}
#demowrap h1 { color: #fff; }
#img {
border-radius: 50%;
width: 256px;
}
#demo {
margin-top: 20px;
background: #000;
}
</style>
<!-- (A) LOAD LIKE/DISLIKE "WIDGET" -->
<link rel="stylesheet" href="lidi.css">
<script src="lidi.js"></script>
<script src="4-demo.js"></script>
</head>
<body>
<!-- (B) DUMMY PRODUCT -->
<div id="demowrap">
<h1>PRODUCT</h1>
<img id="img" src="demo.png">
<div id="demo"></div>
</div>
</body>
</html>
/* (A) WRAPPER */
.lidiWrap {
display: flex;
justify-content: space-around;
align-items: center;
width: 120px;
padding: 15px;
background: #f3f3f3;
}
.lidiWrap.count { width: 250px; }
/* (B) LIKE-DISLIKE BUTTONS */
.lidiUp, .lidiDown {
width: 24px; height: 24px;
background-image: url("lidi.png");
cursor: pointer;
}
.lidiDown { background-position: -48px; }
.lidiUp.set { background-position: -24px; }
.lidiDown.set { background-position: -72px; }
/* (C) LIKE-DISLIKE COUNT */
.lidiUpCount, .lidiDownCount {
font-size: 18px;
color: #858585;
}
function lidi (inst) {
// hWrap : html like/dislike container
// change : function to handle like/dislike toggle change
// status : -1 dislike, 0 neutral, 1 like (optional, default 0)
// count : [likes, dislikes] (optional)
// (A) DEFAULT STATUS + CSS WRAPPER CLASS
if (!inst.status) { inst.status = 0; }
inst.hWrap.classList.add("lidiWrap");
// (B) ATTACH LIKE & DISLIKE BUTTON
inst.hUp = document.createElement("div");
inst.hDown = document.createElement("div");
inst.hUp.className = "lidiUp";
inst.hDown.className = "lidiDown";
if (inst.status==1) { inst.hUp.classList.add("set"); }
if (inst.status==-1) { inst.hDown.classList.add("set"); }
inst.hWrap.appendChild(inst.hUp);
inst.hWrap.appendChild(inst.hDown);
// (C) ATTACH LIKE & DISLIKE COUNT
if (inst.count) {
// (C1) LIKE & DISLIKE COUNT HTML
inst.hUpCount = document.createElement("div");
inst.hDownCount = document.createElement("div");
inst.hUpCount.className = "lidiUpCount";
inst.hDownCount.className = "lidiDownCount";
inst.hUpCount.innerHTML = inst.count[0];
inst.hDownCount.innerHTML = inst.count[1];
inst.hWrap.classList.add("count");
inst.hWrap.insertBefore(inst.hUpCount, inst.hDown);
inst.hWrap.insertBefore(inst.hDownCount, inst.hDown.nextSibling);
// (C2) UPDATE LIKE & DISLIKE COUNT
inst.recount = count => {
inst.count = count;
inst.hUpCount.innerHTML = count[0];
inst.hDownCount.innerHTML = count[1];
};
}
// (D) TOGGLE LIKE/DISLIKE
inst.updown = up => {
// (D1) UPDATE STATUS FLAG
if (up) { inst.status = inst.status == 1 ? 0 : 1; }
else { inst.status = inst.status == -1 ? 0 : -1; }
// (D2) UPDATE LIKE/DISLIKE CSS
if (inst.status==1) {
inst.hUp.classList.add("set");
inst.hDown.classList.remove("set");
} else if (inst.status==-1) {
inst.hUp.classList.remove("set");
inst.hDown.classList.add("set");
} else {
inst.hUp.classList.remove("set");
inst.hDown.classList.remove("set");
}
// (D3) TRIGGER CHANGE
inst.change(inst.status);
};
// (E) ENABLE/DISABLE
inst.enable = () => {
inst.hUp.onclick = () => inst.updown(true);
inst.hDown.onclick = () => inst.updown(false);
};
inst.disable = () => {
inst.hUp.onclick = "";
inst.hDown.onclick = "";
};
inst.enable();
// (F) DONE
return inst;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment