let mysql do work

This commit is contained in:
Bruno Rybársky 2024-04-28 18:16:01 +02:00
parent f28d024bcd
commit 6e7df7f034

@ -162,21 +162,28 @@ function calculateNetVotes(int $memeID): array
{ {
global $mysqli; 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 = $mysqli->prepare($query);
$stmt->bind_param('i', $memeID); $userID = $_SESSION['ID'];
$stmt->bind_param('iii', $memeID, $userID, $memeID);
$stmt->execute(); $stmt->execute();
$result = $stmt->get_result(); $result = $stmt->get_result();
$netVotes = 0; $data = $result->fetch_assoc();
$userVote = 0;
while ($row = $result->fetch_assoc()) { $netVotes = $data['NetVotes'] ?? 0; // Null coalescing operator in case no votes are found
$vote = ($row['isUpvote'] == 1) ? 1 : -1; $userVote = $data['UserVote'] ?? 0; // Default to 0 if the user hasn't voted
$netVotes += $vote;
if ($row['UserID'] == $_SESSION['ID']) {
$userVote = $vote;
}
}
$stmt->close(); $stmt->close();
@ -186,6 +193,7 @@ function calculateNetVotes(int $memeID): array
]; ];
} }
function getMemeVotes(int $memeID): array function getMemeVotes(int $memeID): array
{ {
$voteData = calculateNetVotes($memeID); $voteData = calculateNetVotes($memeID);