I want to create a simple subscription based account management on a PHP and MySQL driven website. I need to keep track of certain types of user accounts and the lengh of the subscriptions. I want the user to be able to select a “subscription package” (bronze, silver, gold) and the timespan (one week, one month, one year) he wants his subscription to last.
However, higher rated subscriptions (gold > silver > bronze) should be given priority over lower rated ones. That means, if a user should have both a silver and a gold subscription, the timespan of the gold subscription should obviously be used first and only when it has run out, should the silver one be used.
To store subscriptions internally, I created a table:
INT id
INT user_id
INT type
DATETIME start
DATETIME end
My question is: How can I find out if a user account has a valid subscription at a certain moment in time and what type that subscription is? Most importantly I would be interested in how to dynamically add more subscriptions when there’s already one subscription runnnig.
More precise example:
- user buys 5 days of bronze on day 1 -> subscription “bronze” runs from day 1-5.
- on day 2, user decides that he wants “silver” additionally and buys another 5 days of that
- situation now: bronze (day 1), silver (days 2-6), bronze (days 7-10)
Preferably, I would like to do most of the work inside a MySQL-query, but I’m not sure if that’s possible at all. If all else fails, I’d have to resort back to PHP.
Thanks for your time!
First, to find the current valid subscriptions, your query should be constructed like:
That will give you daily granularity for the subscriptions. If you want it down to the minute, then take out the times and adjust the date format to be
date("Y-m-d H:i:s")Your result here will be an array of subscriptions for this user, with the highest type first. For evaluating what tier to show, you can just use the first result, which you can find via
$subscriptionRow = mysql_fetch_array($results);When a purchase happens, you’ll have to do a bit more. Basically, iterate through each existing subscription and adjust the time accordingly. Make sure you have not used the above
$subscriptionRowassignment before this code: