Skip to content Skip to sidebar Skip to footer

Php Error Message On Invalid Input

I am new to php I am trying to print an error message If a person insert anything other then a real number in the field. I hope it make sense here is the code, and please describe

Solution 1:

<?php$result = "";
 classcalculator{
   var$a;
   var$b;

   functioncheckopration($oprator)
   {
       switch($oprator)
       {
         case'+':
           return$this->a + $this->b;
           break;

         case'-':
           return$this->a - $this->b;
           break;

         case'*':
           return$this->a * $this->b;
           break;

         case'/':
           return$this->a / $this->b;
           break;

         default:
           return"Sorry No command found";
       }
   }
   functiongetresult($a, $b, $c)
   {
       $this->a = $a;
       $this->b = $b;
       return$this->checkopration($c);
   }
 }

$cal = new calculator();
if(isset($_POST['submit']))
{
  $n1=$_POST['n1'];
  $n2=$_POST['n2'];
  $op=$_POST['op'];
  if(is_numeric($n1)&&is_numeric($n2)){
       $result = $cal->getresult($n1,$n2,$op);
  }else{
    $result="<p style='background-color:#FFCCCC'><b>ERROR: </b>Invalid input</p><br>";
  }
}
?><formmethod="post"><tablealign="center"><tr><td><strong><?phpecho$result; ?><strong></td></tr><tr><td>Enter 1st Number</td><td><inputtype="text"name="n1"></td></tr><tr><td>Enter 2nd Number</td><td><inputtype="text"name="n2"></td></tr><tr><td>Select Oprator</td><td><selectname="op"><optionvalue="+">+</option><optionvalue="-">-</option><optionvalue="*">*</option><optionvalue="/">/</option></select></td></tr><tr><td></td><td><inputtype="submit"name="submit"value="Submit"></td></tr></table></form>

Solution 2:

What you are looking for is the is_numeric() function. Take a look: http://php.net/manual/de/function.is-numeric.php

Solution 3:

using the is_numberic() function in php you can check if the inputed value is a number and if not we can return an error message

<?php$result = "";
 classcalculator{
var$a;
var$b;

functioncheckopration($oprator)
{
    switch($oprator)
    {
        case'+':
        return$this->a + $this->b;
        break;

        case'-':
        return$this->a - $this->b;
        break;

        case'*':
        return$this->a * $this->b;
        break;

        case'/':
        return$this->a / $this->b;
        break;

        default:
        return"Sorry No command found";
    }
}
functiongetresult($a, $b, $c)
{
    $this->a = $a;
    $this->b = $b;
    return$this->checkopration($c);
}
}

$cal = new calculator();
if(isset($_POST['submit']))
{
    if(is_numeric($_POST['n1']) && is_numeric($_POST['n2'])){
        $result = $cal->getresult($_POST['n1'],$_POST['n2'],$_POST['op']);
    }else{
        $result="please only insert numbers into the calculator";
    }
}
?>

Post a Comment for "Php Error Message On Invalid Input"