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.

7
  • Does t_formula have xs or *s in it? Commented Dec 6, 2014 at 16:03
  • * but the site wasn't showing them and i replaced it. Commented Dec 6, 2014 at 16:05
  • 1
    *s are formatting elements in markdown. I edited the question so the variable is displayed properly. Commented Dec 6, 2014 at 16:06
  • 2
    Be mindful using eval() Commented Dec 6, 2014 at 16:08
  • 1
    1000;echo DB_PASSWORD;echo DB_USERNAME; Commented Dec 6, 2014 at 16:12

2 Answers 2

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); 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@davco98 take care with the edit of the answer, I added ; at the last to the string to be valid PHP code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.