-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvote.php
More file actions
71 lines (61 loc) · 2.92 KB
/
vote.php
File metadata and controls
71 lines (61 loc) · 2.92 KB
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
<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Include database connection file
include 'db_connection.php';
// Get the JSON input
$input = json_decode(file_get_contents('php://input'), true);
// Extract variables
$blogId = mysqli_real_escape_string($conn, $input['blogId']);
$userId = mysqli_real_escape_string($conn, $input['userId']);
$voteType = mysqli_real_escape_string($conn, $input['voteType']);
// Fetch current vote for the user
$sql_fetch_vote = "SELECT vote_type FROM USER_VOTES WHERE blog_id='$blogId' AND user_id='$userId'";
$result_fetch_vote = mysqli_query($conn, $sql_fetch_vote);
$currentVote = mysqli_fetch_assoc($result_fetch_vote);
if ($currentVote) {
// If user has already voted
if ($currentVote['vote_type'] !== $voteType) {
// Update their vote
$sql_update_vote = "UPDATE USER_VOTES SET vote_type='$voteType' WHERE blog_id='$blogId' AND user_id='$userId'";
mysqli_query($conn, $sql_update_vote);
if ($currentVote['vote_type'] === 'upvote') {
$sql_update_counts = "UPDATE BLOGS SET upvotes = upvotes - 1, downvotes = downvotes + 1 WHERE blog_id='$blogId' AND user_id='$userId'";
} else {
$sql_update_counts = "UPDATE BLOGS SET upvotes = upvotes + 1, downvotes = downvotes - 1 WHERE blog_id='$blogId' AND user_id='$userId'";
}
mysqli_query($conn, $sql_update_counts);
}
} else {
// If user has not voted yet, insert their vote
$sql_insert_vote = "INSERT INTO USER_VOTES (blog_id, user_id, vote_type) VALUES ('$blogId', '$userId', '$voteType')";
mysqli_query($conn, $sql_insert_vote);
if ($voteType === 'upvote') {
$sql_update_counts = "UPDATE BLOGS SET upvotes = upvotes + 1 WHERE blog_id='$blogId' AND user_id='$userId'";
} else {
$sql_update_counts = "UPDATE BLOGS SET downvotes = downvotes + 1 WHERE blog_id='$blogId' AND user_id='$userId'";
}
mysqli_query($conn, $sql_update_counts);
}
// Get updated vote counts
$sql_fetch_counts = "SELECT upvotes, downvotes FROM BLOGS WHERE blog_id='$blogId' AND user_id='$userId'";
$result_fetch_counts = mysqli_query($conn, $sql_fetch_counts);
$counts = mysqli_fetch_assoc($result_fetch_counts);
// Return updated counts as JSON response
echo json_encode([
'success' => true,
'upvoteCount' => $counts['upvotes'],
'downvoteCount' => $counts['downvotes'],
]);
// Close connection
mysqli_close($conn);
} else {
// Method not allowed
http_response_code(405);
echo json_encode(['error' => 'Method Not Allowed']);
}
?>