0

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.

davco98
  • 31
  • 5

2 Answers2

1

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);
Ananth
  • 4,227
  • 2
  • 20
  • 26
0

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

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • @davco98 take care with the edit of the answer, I added `;` at the last to the string to be valid PHP code. – SaidbakR Dec 06 '14 at 16:17