Reputation: 31
I'm working in an invoice system, that has to calculate different formulas for every product, which will need to be filled with Width, Height, and Material cost.
I did a database where i'm storing
t_title -> "Curtain 1"
t_formula -> "({ANCHO}*{ALTURA})*{PRECIO}"
and then php does this:
<?php
$ancho = str_replace("{ANCHO}", $_POST['ancho'], $articulo['t_formula']);
$alto = str_replace("{ALTURA}", $_POST['alto'], $ancho);
$precio = str_replace("{PRECIO}", $_POST['precio'], $alto);
$total = $precio; echo eval($total);
?>
and the result is not giving anything, but a blank space.
How can i make it to work? I know that php can't calculate from variables as php but, i can't find another way to do it.
Upvotes: 0
Views: 1990
Reputation: 4407
The eval() function expects the string parameter to be a proper code statement.
$str = '(10*10) * 1000';
echo eval($str);
will give you an error, because php cannot evaluate that string. However,
$str = 'return (10*10) * 1000;';
echo eval($str);
will evaluate the expression correctly.
You should use:
$total = 'return ' . $precio . ';';
echo eval($total);
Upvotes: 1
Reputation: 13552
Your using eval
is wrong. The string passed to eval must be valid PHP code. i.e:
$precio2 = '$total = '.$precio.';';
eval($precio2);
echo $total;
http://php.net/manual/en/function.eval.php
Upvotes: 0