Calculation in php giving error

2

On my site I have the following code to calculate discounts:

$valor_a_ser_calculado =$_POST['loc']; // valor original
$quantos_porcento = 75/100; //isso equivale a 7% 
$loc = $quantos_porcento * $valor_a_ser_calculado . "\n";

Only you are giving the following error:

PHP Warning:  A non-numeric value encountered in /home/jp/public_html/orcamento.php on line 6

I would like to know how to resolve this.

    
asked by anonymous 14.12.2017 / 23:25

1 answer

3

You have two immediate problems in the code: You are not verifying that the POST value is correct, and blending multiplication with concatenation. Test this:

$valorasercalculado = $_POST['loc']; // valor original
echo "Valor original: $valorasercalculado <br>";

$quantos_porcento = 75/100; //isso equivale a 7.5% 
echo "Porcentagem: $quantosporcento <br>";

$loc = $quantos_porcento * $valor_a_ser_calculado;
echo "Resultado: $loc <br>";

In this case, it will only have warnings if any of the values are not numeric.

The ideal would be to rethink something along these lines:

$valorasercalculado = isset($_POST['loc']) ? $_POST['loc'] : 0;

Or even

if (!isset($_POST['loc'])) die 'Valor não fornecido';

at the beginning of the code.

As well remembered by @RafaelSalomao, PHP has a specific function to test if a value is numeric. Putting together the two ideas:

if (!isset($_POST['loc'])) die 'Valor não fornecido';
if (!is_numeric($_POST['loc'])) die 'O valor precisa ser numérico';

(remembering that before the function means "not", in the cases above, if the value is NOT set, the script stops.) If the value is NOT numeric, the script also stops.

Manual:

  

link

  

link

    
14.12.2017 / 23:36