-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlikes.php
71 lines (59 loc) · 2.79 KB
/
likes.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
<?php
include 'header.php';
header('Content-Type: application/json'); // Set appropriate response header
$conn = new mysqli($servernamesql, $usernamesql, $passwordsql, $databasesql);
$zero = 1; // Initialize likeCount variable
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$postId = $_POST['post_id'] ?? 0;
$type = $_POST['type'];
// Validate and sanitize $postId and $type (add your validation here)
if (!empty($postId)) {
// Check if the post already has a like (value of 0), then update it by one
// Retrieve the current value of postid from the database
$selectQuery = "SELECT postid, itemid FROM likes WHERE itemid = ? and type = ?";
$selectStmt = mysqli_prepare($conn, $selectQuery);
mysqli_stmt_bind_param($selectStmt, 'is', $postId, $type);
mysqli_stmt_execute($selectStmt);
mysqli_stmt_store_result($selectStmt);
mysqli_stmt_bind_result($selectStmt, $likesId, $itemId);
// Check the number of rows returned
$numRows = mysqli_stmt_num_rows($selectStmt);
// If the row with the given postid exists, increment the value
if ($numRows > 0) {
$selectStmt->fetch(); // Fetch the results
$totallikes = $likesId + 1;
// Update the database
$updateQuery = "UPDATE likes SET postid = ? WHERE itemid = ? and type = ?";
$updateStmt = mysqli_prepare($conn, $updateQuery);
if ($updateStmt) {
mysqli_stmt_bind_param($updateStmt, 'iis', $totallikes, $itemId, $type);
mysqli_stmt_execute($updateStmt);
mysqli_stmt_close($updateStmt);
$likeCount = $totallikes; // Set the updated like count
} else {
// Handle the case where mysqli_prepare failed.
echo json_encode(array('error' => 'Error preparing statement: ' . mysqli_error($conn)));
exit;
}
} else {
// Insert a new like record into the 'likes' table
$insertQuery = "INSERT IGNORE INTO likes (itemid, userid, postid, type) VALUES (?, ?, ?, ?)";
$insertStmt = mysqli_prepare($conn, $insertQuery);
$userId = $_SESSION['userid'];
mysqli_stmt_bind_param($insertStmt, 'iiis', $postId, $userId, $zero, $type);
mysqli_stmt_execute($insertStmt);
mysqli_stmt_close($insertStmt);
// Since it's a new like, set likeCount to 1
$likeCount = 1;
}
$response = array('likecount' => $likeCount);
echo json_encode($response);
} else {
echo json_encode(array('error' => 'Invalid post ID'));
}
} else {
echo json_encode(array('error' => 'Invalid request method'));
}
// Close the database connection
mysqli_close($conn);
?>