-1

This is my code:

public function test(){

    $type = 'test';
    $a = '1';
    $b = '1';

    $formula = $this->Dashboard_Model->formula($type);

    $answer = $formula->FORMULA;

    //echo $answer;

}

All it does is get the formula that I stored into my database. I can properly get the formula I want. And for this test function the formula is $a+$b

Now I want that formula to become a PHP code and output the answer. How can I do it?

I want it so that whatever formula I want, I can use it, and update it whenever I wanted to.

Thanks.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
kev_m
  • 325
  • 7
  • 30
  • Unclear what you asking – Abdulla Nilam Aug 05 '16 at 13:40
  • You could use [eval](http://php.net/manual/en/function.eval.php) (not really a good thing to do, though) – FirstOne Aug 05 '16 at 13:40
  • @FirstOne can you explain it a little further? – kev_m Aug 05 '16 at 13:41
  • Like this: [https://eval.in/618525](https://eval.in/618525). But I'd try other things before using `eval`. Does the formula come from user input? – FirstOne Aug 05 '16 at 13:45
  • yes. i do want it to be input by me.. – kev_m Aug 05 '16 at 13:46
  • Sure, keep your sentences to the minimum, that will make people understand you (sarcasm).. I've linked the manual, read it! Altough it does what you want, it's a dangerous function.. use it at your own risk ;) – FirstOne Aug 05 '16 at 13:48
  • 1
    why is it a dangerous function? – kev_m Aug 05 '16 at 13:49
  • RTFM.. I'm not responding anymore unless you do! (I even linked it for you) – FirstOne Aug 05 '16 at 13:51
  • possible duplicates: [calculate math expression from a string using eval](http://stackoverflow.com/questions/18880772/calculate-math-expression-from-a-string-using-eval) **&&** [PHP function to evaluate string like “2-1” as arithmetic 2-1=1](http://stackoverflow.com/questions/5057320/php-function-to-evaluate-string-like-2-1-as-arithmetic-2-1-1) – FirstOne Aug 05 '16 at 14:01

1 Answers1

0

I have added a number_format function around the result as this will make sure that you have a number returned instead of naughty code.

public function test(){

    $type = 'test';
    $a = '1';
    $b = '1';

    $formula = $this->Dashboard_Model->formula($type);

    $answer = $formula->FORMULA;

    echo number_format(eval($answer), 2);

}

The above code will make sure a number is returned.

eval evaluates (executes) a string as PHP code. Your database may have malicious code instead of a formula.

beingalex
  • 2,416
  • 4
  • 32
  • 71