Search code examples
phpdiscount

Discount calculation


I'm currently designing a database for my company's website. I would like to create a table which will hold information (logic) about our discounts so that I can just call a function with a discountID and my php code will calculate the new price. My question is, every discount has different logic. ex. 10% off, $10 off, by one get one free, buy 3 get 50% off...

How can I store this in the database so that my code can calculate the discount on its own?


Solution

  • A database does not store logic - only data. Split this into three fields:

    • discount amount (int)
    • discount type (enum; possible values: 'percent', 'amount')
    • buy one get N free (int; the number you get free for every one bought)

    So for one discount you might store the following:

    | discount amount | discount type | buy one get one free |
    ----------------------------------------------------------
    |       10        |   'percent'   |                      |
    

    For another, where BOGOF applies:

    | discount amount | discount type | buy one get N free |
    ----------------------------------------------------------
    |                 |               |         1          |
    

    Then it would be up to your PHP to receive these values and act accordingly.