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;
}
};
?>
Use empty() to check field, because when you sending empty form fields always isset.
strcmp() strcmp returns 0 when strings are equal, so you need use that if statement
I prefer switch statement for that operations.