0

In my PHP file, a have these variables: $a, $b, $c and $d.

Depending on the mode a user selects, a different formula should be used to calculate a certain number. I would like to store these formulas in a MySQL database:

ID      /      Mode      /      Formula

mode1      namemode1        $a*$b/$c+$d
mode2      namemode2    /   $a/$b+$c+$d
etc.

How could I make the string I get when I select it from the database into PHP variables? Is there sort of a best practice for this?

binoculars
  • 2,226
  • 5
  • 33
  • 61
  • If you know in advance all the formulae (and their number is not very large), I suggest you to assign a number to each formula, store the number in the database and write a PHP function that, given the formula number and the values, computes the result using the correct formula. – axiac Dec 11 '16 at 18:28
  • Unfortunately, that's not possible: someone without programming knowledge will add new modes every few weeks. I want this to be possible without the need of updating the PHP code. – binoculars Dec 11 '16 at 18:31
  • 2
    If you're looking for best practice; it's what @axiac suggested, If you just want it to work as you described then use eval http://php.net/eval which will open your code/system to all kind of hacks – ahmad Dec 11 '16 at 18:35
  • Thanks for the suggestion! I'll use `eval()`. Since the string that needs evaluation will never be user input, I guess it's not dangerous to use here, but do correct me if I'm wrong. – binoculars Dec 11 '16 at 19:49
  • 2
    You're not after `eval`, even though it's the easiest approach. What you need is **equation engine**. You need a way to store an equation to your db, then replace its variables with actual values, while none of it is real PHP code. Refer to [this answer](http://stackoverflow.com/a/16071456/693806) and [EOS library](https://github.com/jlawrence11/eos) on GitHub because that's what you're after. – N.B. Dec 11 '16 at 22:35

1 Answers1

0

You could store the formula by converting it to string. Convert php code to string which is opposite to eval()- has been exaplained here: Convert php code to string, opposite to eval()

Community
  • 1
  • 1
rapidRoll
  • 300
  • 1
  • 9