Vishal Vishwakarma
Vishal Vishwakarma

Reputation: 336

how to store a formula in a table and use as php variable to do mathematical operations?

I want to use PHP variables in the formula that came from the database data.

I want to do mathematical logic using a database so users can change the whole logic of output using those variables.

if any clarification is needed you can comment.

thanks in advance :)

<?php
    
    include '../../db.php';
    
    $a = 50;
    $b = 20;
    $c = 30;
    
    $fq = $conn->query("SELECT * FROM `test`");
    $fdata = $fq->fetch_array();
    $formula = $fdata['formula'];
    
    echo $output = $formula;
    
?>

Database table

Database table example

Current Output

$a+$b-$c

Expected Output

40

Upvotes: 1

Views: 289

Answers (2)

N69S
N69S

Reputation: 17216

You can use it with eval() but that's a bad idea.

$result = eval($fdata['formula']);

Some servers with shared hosting will prohibit the use of such method and ones like exec().

One clever idea if you have a limited number of operation types ("+", "-", "*", "/") is to explode your string piece by piece and then process them.

A simple example would be

$x = '$a+$b*$c';
$summArray = explode('+', $x);
foreach($summArray as $key => $item) {
    $multiplyArray = ('*', $item);
    if (count($multiplyArray) > 1) {
        $summArray[$key] = $multiplyArray;
    }
}

//now to process
$values = ['$a' => $a, '$b' => $b, '$c' => $c];
$result = 0;
foreach($summArray as $item) {
    if (is_array($item)) {
        $multResult = 1;
        foreach($item as $multItem) {
            $multResult *= $values[$multItem]
        }
        $result += $multResult;
    } else {
        $result += $values[$item];
    }
}

something like that

Upvotes: 3

ChampionSemi SEO
ChampionSemi SEO

Reputation: 152

<?php
    
    include '../../db.php';
    
    $a = 70;
    $b = 20;
    $c = 30;
    
    $fq = $conn->query("SELECT * FROM `test`");
    $fdata = $fq->fetch_array();
    $formula = $fdata['formula'];
    
    echo $result = eval('return '.$formula.';');
    
?>

above code will help you in doing the same.

eval('return '.$formula.';')

just need to replace this.

Upvotes: -2

Related Questions