October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Spend a Wallet Balance First, Then Earnings in PHP

Calculate a purchase across wallet and earnings by spending the wallet first, deducting only the shortfall from earnings, and saving all changes together.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To charge a purchase from a wallet first and use earnings only for the shortfall, split the purchase amount between the two balances. Reject the purchase only when their combined value is too small. Deduct each share once, and save the purchase and both updated balances together so a partial failure cannot leave the account inconsistent.

Calculate the wallet-first deduction

Let $amount be the purchase total, and keep $wallet and $earnings numeric while calculating. First test whether the two balances together cover the purchase. If they do, use as much as possible from the wallet, then take any remaining amount from earnings:

As an Amazon Associate I earn from qualifying purchases.

$total = $wallet + $earnings;

if ($total < $amount) {
    // Reject the purchase: combined funds are insufficient.
} elseif ($wallet >= $amount) {
    // Wallet covers the whole purchase.
    $wallet -= $amount;
} else {
    // Use the wallet's full balance and charge the shortfall to earnings.
    $remaining = $amount - $wallet;
    $wallet = 0;
    $earnings -= $remaining;
}

The first branch handles insufficient combined funds. The second leaves earnings unchanged when the wallet covers the cost. The final branch applies when the wallet is too small on its own but both balances together are sufficient. This is the wallet-first reversal of the earnings-first approach discussed in the SitePoint thread.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An equivalent calculation makes the two shares explicit:

$fromWallet = min($wallet, $amount);
$fromEarnings = $amount - $fromWallet;

$newWallet = $wallet - $fromWallet;
$newEarnings = $earnings - $fromEarnings;

Use this version only after confirming $wallet + $earnings >= $amount; otherwise the earnings share could exceed the available earnings. It can be useful when the purchase record needs to show how much came from each source.

Avoid double deductions and lost remainders

Each balance should be reduced only by the portion of the purchase paid from that balance. Subtracting the full $amount from both wallet and earnings charges the customer twice and can make a balance negative. The original troubleshooting discussion highlights this mistake and the related issue of setting $wallet = 0; after subtracting from it: the assignment discards any remainder that the subtraction was meant to preserve. See the thread discussion.

Keep the calculation in distinct steps rather than combining assignments and arithmetic into a single expression. For example, an expression that assigns a wallet value and an earnings value in the same arithmetic statement does not clearly represent “spend the wallet, then deduct the remainder from earnings.” Intermediate values make the order and amounts auditable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Save the purchase and balances consistently

The calculation alone does not protect stored data. If the purchase insert succeeds but one balance update fails—or one balance changes without the purchase being recorded—the account can become inconsistent. Within a database transaction, update both balance fields and insert the purchase records; commit only if all required operations succeed, and roll back if any fails. The SitePoint continuation recommends committing only after the video records and balance updates succeed, but it does not establish a particular schema or framework-specific transaction code.

  • Calculate each balance’s deduction once.
  • Persist the purchase and both resulting balances as one all-or-nothing unit.
  • Format monetary values only at persistence or display boundaries; keep values numeric during the calculation.

Separate PHP errors from application-level errors

A browser message such as “Something went wrong” may come from the request failing at the HTTP level rather than from the JSON error branch that checks data.error_num. In the thread’s continuation, the jQuery .fail() handler is associated with a response that is not HTTP 200. Check the browser’s Network panel for the request’s HTTP status and response body, then inspect any PHP error text before changing the balance logic. The continuation on the failure handler discusses this distinction.

Also check the braces around the relevant if/elseif block. A misplaced or missing closing brace can change which code runs and may lead to the wrong request path or error response; the thread’s code review flags this possibility.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What the example does not decide

The calculation assumes both values represent compatible amounts in the same currency and that $amount is a valid nonnegative purchase total. The 2019 SitePoint discussion does not specify the site’s currency rules, database schema, PHP or framework version, or transaction-isolation requirements, so those details must be handled by the application. The thread is community troubleshooting, not an official PHP specification or a verified production patch.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.