samedi 31 décembre 2016

Validate fields with isset

I try to create a basic calculator, and that works perfectly but i need validate the fields. I' trying with if() but php ignores this. If fields is empty not showing the menssage 'Complete all fields' and execute the function operadora(); resulting 0.

What am I doing wrong?

Sorry for my bad english :(

This is the form:

<form action="calcular.php" method="post">
<input name="valor1" type="number">
  <select name="operacion" id="">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
   </select>
<input name="valor2" type="number">
<input type="submit" name="enviar" value="enviar">
</form>

And this is the php code:

<?php

if(isset($_POST['enviar'])){
  if(!isset($_POST['valor1']) ||
  !isset($_POST['valor2'])){
    echo 'complete all fields';
  }
  else{
    $valor1 = $_POST['valor1'];
    $valor2 = $_POST['valor2'];
    $operacion = $_POST['operacion'];
    operadora($operacion,$valor1,$valor2);
  }
}

function operadora($operador, $valor1, $valor2){
if(!strcmp($operador,"+")){
     $resultado = $valor1+$valor2;
     echo $resultado;
   }
if(!strcmp($operador,"-")){
     $resultado = $valor1-$valor2;
     echo $resultado;
   }
if(!strcmp($operador,"*")){
     $resultado = $valor1*$valor2;
     echo $resultado;
   }
if(!strcmp($operador,"/")){
     $resultado = $valor1/$valor2;
     echo $resultado;
   }
};

 ?>

Aucun commentaire:

Enregistrer un commentaire