从数据库获取公式并使用它

时间:2016-08-05 13:38:51

标签: php codeigniter

这是我的代码:

public function test(){

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

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

    $answer = $formula->FORMULA;

    //echo $answer;

}

所有这一切都是得到我存储到我的数据库中的公式。我可以正确地得到我想要的公式。对于此测试函数,公式为$a+$b

现在我希望该公式成为PHP代码并输出答案。我该怎么办?

我想要它,以便无论我想要什么样的公式,我都可以使用它,并在我想要的时候更新它。

感谢。

1 个答案:

答案 0 :(得分:0)

我在结果周围添加了number_format函数,因为这样可以确保返回的是一个数字,而不是顽皮的代码。

public function test(){

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

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

    $answer = $formula->FORMULA;

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

}

上面的代码将确保返回一个数字。

eval将字符串作为PHP代码进行评估(执行)。您的数据库可能包含恶意代码而不是公式。

相关问题