let mysql do work
This commit is contained in:
parent
f28d024bcd
commit
6e7df7f034
30
lib/meme.php
30
lib/meme.php
@ -162,21 +162,28 @@ function calculateNetVotes(int $memeID): array
|
||||
{
|
||||
global $mysqli;
|
||||
|
||||
$query = 'SELECT isUpvote, UserID FROM MemeVotes WHERE MemeID = ?';
|
||||
// Adjusted query to calculate net votes and get the user's vote in one go
|
||||
$query = "
|
||||
SELECT
|
||||
SUM(CASE WHEN isUpvote = 1 THEN 1 ELSE -1 END) AS NetVotes,
|
||||
(
|
||||
SELECT CASE WHEN isUpvote = 1 THEN 1 ELSE -1 END
|
||||
FROM MemeVotes
|
||||
WHERE MemeID = ? AND UserID = ?
|
||||
) AS UserVote
|
||||
FROM MemeVotes
|
||||
WHERE MemeID = ?";
|
||||
|
||||
$stmt = $mysqli->prepare($query);
|
||||
$stmt->bind_param('i', $memeID);
|
||||
$userID = $_SESSION['ID'];
|
||||
$stmt->bind_param('iii', $memeID, $userID, $memeID);
|
||||
$stmt->execute();
|
||||
$result = $stmt->get_result();
|
||||
|
||||
$netVotes = 0;
|
||||
$userVote = 0;
|
||||
while ($row = $result->fetch_assoc()) {
|
||||
$vote = ($row['isUpvote'] == 1) ? 1 : -1;
|
||||
$netVotes += $vote;
|
||||
if ($row['UserID'] == $_SESSION['ID']) {
|
||||
$userVote = $vote;
|
||||
}
|
||||
}
|
||||
$data = $result->fetch_assoc();
|
||||
|
||||
$netVotes = $data['NetVotes'] ?? 0; // Null coalescing operator in case no votes are found
|
||||
$userVote = $data['UserVote'] ?? 0; // Default to 0 if the user hasn't voted
|
||||
|
||||
$stmt->close();
|
||||
|
||||
@ -186,6 +193,7 @@ function calculateNetVotes(int $memeID): array
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
function getMemeVotes(int $memeID): array
|
||||
{
|
||||
$voteData = calculateNetVotes($memeID);
|
||||
|
Loading…
Reference in New Issue
Block a user