Validate fields with isset

84 views Asked by At

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;
   }
};

 ?>
2

There are 2 answers

3
Mirek Kowieski On BEST ANSWER

Use empty() to check field, because when you sending empty form fields always isset.

if (!empty($_POST['valor1') 
    && !empty($_POST['valor2']) 
    && !empty($_POST['operacion'])) {

    $valor1 = $_POST['valor1'];
    $valor2 = $_POST['valor2'];
    $operaction = $_POST['operaction'];
    operadora($operaction, $valor1, $valor2);
} else {
    echo 'Complete all fields';
}

strcmp() strcmp returns 0 when strings are equal, so you need use that if statement

if (strcmp($operador, "+") == 0) {
    $resultado = $valor1 + $valor2;
    echo $resultando;
}

I prefer switch statement for that operations.

function operadora($operador, $valor1, $valor2)
{
    $resultado = 0;
    switch($operador) {
        case '+':
            $resultado = $valor1 + $valor2;
            break;
        case '-':
            $resultado = $valor1 - $valor2;
            break;
        case '*':
            $resultado = $valor1 * $valor2;
            break;
        case '/':
            $resultado = $valor1 / $valor2;
            break;
    }
    echo $resultado;
}
0
Ali Rasheed On

Try this

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