From 6e7df7f03461cd39b2ed3ee575d4dbb2c8475f69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ryb=C3=A1rsky?= Date: Sun, 28 Apr 2024 18:16:01 +0200 Subject: [PATCH] let mysql do work --- lib/meme.php | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/lib/meme.php b/lib/meme.php index 8f6cd69..4ce4293 100644 --- a/lib/meme.php +++ b/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);