From a9e443eeb2dfdfc4c366ec102598e47ab6a79194 Mon Sep 17 00:00:00 2001 From: Keith Solomon Date: Mon, 3 Aug 2026 22:17:11 -0500 Subject: [PATCH] vaultLoop: use MAX(running_balance) per user instead of SUM(amount) --- includes/utilities.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/includes/utilities.php b/includes/utilities.php index d6cd900..788307b 100644 --- a/includes/utilities.php +++ b/includes/utilities.php @@ -200,14 +200,22 @@ function fetchVaultRecords($user = null) { * @return int The total balance of the given user (or all users if no user is given). */ function vaultLoop ($name=null) { - $vault = fetchVaultRecords($name); - $balance = 0; + $pdo = getDatabaseConnection(); - foreach ($vault as $entry) { - $balance += $entry['amount']; + if ($name === null) { + $stmt = $pdo->query( + 'SELECT COALESCE(SUM(max_balance), 0) FROM ' + . '(SELECT MAX(running_balance) AS max_balance FROM vault GROUP BY user)' + ); + + return (int)$stmt->fetchColumn(); } - return $balance; + $stmt = $pdo->prepare('SELECT MAX(running_balance) FROM vault WHERE user = :user'); + $stmt->bindValue(':user', $name); + $stmt->execute(); + + return (int)$stmt->fetchColumn(); } /**