Skip to content

Instantly share code, notes, and snippets.

@Dayjo
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dayjo/2691817721be8503aba5 to your computer and use it in GitHub Desktop.
Save Dayjo/2691817721be8503aba5 to your computer and use it in GitHub Desktop.
Script to update subscription vat rates based on last invoice
<?php
// Get everyone's "last subscription invoice" for people who've paid in the last year
$sql = "SELECT i1.vatrate, i1.username
FROM invoices i1
LEFT JOIN invoices i2 ON (i1.username = i2.username AND i1.id < i2.id)
WHERE i2.id IS NULL
AND i1.datestamp > '2014-04-01'
AND i1.type IN ('sub','subpayment','upgrade','resubscription')
ORDER BY i1.vatrate DESC";
$r = xdb::query($sql);
// Loop through each user
while ( $invoice = xdb::fetch_array($r)) {
// Update the user's subscription vatrate
$update = "UPDATE subscriptions
JOIN sites on subscriptions.siteid = sites.id
JOIN users ON users.ID = sites.userid
SET vatrate = '" . $invoice['vatrate'] . "'
WHERE users.username = '" . xdb::escape($invoice['username']) . "'";
$doit = xdb::query($update);
// Debug output
echo $invoice['username'] . ".. ";
}
@AidanThreadgold
Copy link

Why do you need the join in the select?

@Dayjo
Copy link
Author

Dayjo commented Apr 9, 2015

@AidanThreadgold Because It's getting the 'last' invoice for each user, and I used this method over a sub query.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment