-
Notifications
You must be signed in to change notification settings - Fork 0
/
upvote.php
85 lines (72 loc) · 2.64 KB
/
upvote.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
83
84
85
<?php
// check if user is logged in
session_start();
if(!isset($_SESSION['sessionId'])){
header('location: login.php?status=not_logged_in');
exit;
}
require_once("controllers/database.php");
$postId = $_POST['p_id'];
$loggedInUserId = $_SESSION['userId'];
$upvoteId = uniqid();
// if someone clicked upvote then
// if(the upvote is not there){
// write to the upvotes table } else {
// delete the upvote from the table
// }
$done = false;
//go to database and see if this post has already been liked by the logged in user
try{
$stmt = $db->prepare('SELECT * FROM upvotes WHERE id_posts = :upvotedPost AND id_users = :loggedInUserId');
$stmt->bindValue(':upvotedPost', $postId);
$stmt->bindValue(':loggedInUserId', $loggedInUserId);
$stmt->execute();
$users = $stmt->fetchAll();
} catch (PDOException $ex){
// echo 'error selecting upvotes: '.$ex;
//recirect either to index or gag.php
exit();
}
if(count($users) == 0){
// echo 'like';
try{
$stmt2 = $db->prepare('INSERT INTO upvotes(id_upvotes, id_posts, id_users) VALUES (:id_upvotes, :id_posts, :id_users)');
$stmt2->bindValue(':id_upvotes', $upvoteId);
$stmt2->bindValue(':id_posts', $postId);
$stmt2->bindValue(':id_users', $loggedInUserId);
$stmt2->execute();
$done = true;
} catch (PDOException $ex){
// echo 'error saving upvote: '.$ex;
exit();
}
} else {
// echo 'this post has been liked by you already';
try{
$stmt = $db->prepare('DELETE FROM upvotes WHERE id_posts = :upvotedPost AND id_users = :loggedInUserId');
$stmt->bindValue(':upvotedPost', $postId);
$stmt->bindValue(':loggedInUserId', $loggedInUserId);
$stmt->execute();
$done = true;
} catch (PDOException $ex){
// echo 'error deleting upvote: '.$ex;
//recirect either to index or gag.php
exit();
}
}
//return to ajax number of upvotes for this post
if($done){
try{
$stmt = $db->prepare('SELECT COUNT(*) AS new_upvotes_count FROM upvotes WHERE id_posts = :upvotedPost');
$stmt->bindValue(':upvotedPost', $postId);
$stmt->execute();
$aaUpvotesAfterChange = $stmt->fetchAll();
} catch (PDOException $ex){
// echo 'error selecting upvotes: '.$ex;
//recirect either to index or gag.php
exit();
}
$aUpvotesAfterChange = $aaUpvotesAfterChange[0];
$iNumberOfUpvotes = $aUpvotesAfterChange['new_upvotes_count'];
echo $iNumberOfUpvotes;
}