YTe
YTe

Reputation: 31

PHP / Save math formula in table row

I am managing an online store. Every products has his own fees calculation (1% + 0.10€ / 1% + 0.20€ / 1% + 0.30€ etc). I'm not able to guess right now what are fees because we follow complex calculations and can't integrate them directly in a PHP class.

I would like, in my back-end, to be able to add formulas and to assign them to every product. Example: For product A, I would like to create the fee calculation "X/100+0.10" where X is the product price. How can I store this kind of formula in a SQL row? Is it safe? How can I tell to PHP to use this row as:

    $fee = X/100 + 0.1;

Thanks!

Upvotes: 2

Views: 2537

Answers (1)

IaMaCuP
IaMaCuP

Reputation: 845

So as a rule of thumb, you can store whatever you want in the database - don’t be worried about what you can store in there, what you need to worry about is how you store it - the database just understands types of data, not the meaning of that data - so to answer your question, yes it is safe to store that string in the database (assuming you put stuff in your database using the correct escape methods etc.)

To be honest without more knowledge of how many different calculations we are talking about, this is quite a hard one - in an ideal world you would have a field in the database for each different variable / exponent in the calculation and then assemble this at the PHP end, however given you have stated that this can be complicated - something like this might work for a generic case, although it leaves a lot to be desired:

lets say you store stuff in your database like this

$formula = ‘X/100 + 0.1’;

insertIntoDatabase($formula);

—— some time later

$resultsOfQuery = someDatabaseMethod();

foreach($resultsOfQuery as $row)
{
    $calculation = str_replace(‘X’, $row[‘price’], $row[‘formula’]);
    //here $calculation now contains something like ’22.1/100 + 1’;
}

now, in our foreach loop $calculation contains something like ’22.1/100 +1’ which needs evaluation - you can do this in a number of ways - this SO post explains it: PHP function to evaluate string like "2-1" as arithmetic 2-1=1

This is only 1 way, there are many - have a fiddle and see what works for you.

Upvotes: 3

Related Questions