-
Notifications
You must be signed in to change notification settings - Fork 0
/
like_image.php
58 lines (48 loc) · 1.61 KB
/
like_image.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
<?php
require_once "./config/database.php";
// Login information
session_start();
if (!isset($_SESSION['loggued_on_user']))
return ;
// This file will update the like for each image given in the $_POST
$login = $_SESSION['loggued_on_user'];
$img_name = $_POST['img_name'];
// Connect to database
try {
$dbh = new PDO($DB_DSN, $DB_USER, $DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
return ;
}
// Check if user already liked image
$sql = "SELECT COUNT(*) FROM Likes
WHERE `img_name` = :img_name AND `user_login` = :login";
$sth = $dbh->prepare($sql);
$sth->execute(array(':img_name' => $img_name, ':login' => $login));
$val = $sth->fetchColumn();
if (strcmp($val,'0')) {
// Unlike the photo in the Likes table
$sql = "DELETE FROM `Likes`
WHERE `img_name` = :img_name
AND `user_login` = :user_login;";
$sth = $dbh->prepare($sql);
$sth->execute(array(':user_login' => $login, ':img_name' => $img_name));
}
else {
// Like the photo in the Likes table
$sql = "INSERT INTO Likes (img_name, user_login) VALUES (:img_name, :user_login);";
$sth = $dbh->prepare($sql);
$sth->execute(array(':user_login' => $login, ':img_name' => $img_name));
}
// Getting nb of likes for this image
$sql = "SELECT COUNT(Likes.img_name) AS 'nb_of_likes' FROM Likes
WHERE `img_name` = :img_name";
$sth = $dbh->prepare($sql);
$sth->execute(array(':img_name' => $img_name));
$f = $sth->fetch();
$nb_of_likes = $f['nb_of_likes'];
// Echo number of like after like or unlike
echo "Like ($nb_of_likes)";
$dbh = null;
?>