-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreactions.php
82 lines (75 loc) · 2.25 KB
/
reactions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
class Reactions {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo;
private $stmt;
public $error;
function __construct () {
try {
$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
]
);
} catch (Exception $ex) { exit($ex->getMessage()); }
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
$this->pdo = null;
$this->stmt = null;
}
// (C) GET REACTIONS FOR ID
function get ($id, $uid=null) {
// (C1) GET TOTAL REACTIONS
$results = ["react" => [0, 0]]; // [LIKES, DISLIKES]
$this->stmt = $this->pdo->prepare(
"SELECT `reaction`, COUNT(`reaction`) `total`
FROM `reactions` WHERE `id`=?
GROUP BY `reaction`"
);
$this->stmt->execute([$id]);
while ($row = $this->stmt->fetch()) {
if ($row["reaction"]==1) { $results["react"][0] = $row["total"]; }
else { $results["react"][1] = $row["total"]; }
}
// (C2) GET REACTION BY USER (IF SPECIFIED)
if ($uid !== null) {
$this->stmt = $this->pdo->prepare(
"SELECT `reaction` FROM `reactions` WHERE `id`=? AND `user_id`=?"
);
$this->stmt->execute([$id, $uid]);
$results["user"] = $this->stmt->fetchColumn();
}
return $results;
}
// (D) SAVE REACTION
function save ($id, $uid, $react) {
// (D1) 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];
}
// (D2) EXECUTE SQL
try {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
return true;
} catch (Exception $ex) {
$this->error = $ex->getMessage();
return false;
}
}
}
// (E) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (F) CREATE NEW CONTENT OBJECT
$_REACT = new Reactions();