0

I'm new to PHP. I am coding for simple Cuboid Calculator. I have to show error message if length, breadth, and height is negative, empty or not numeric.

I have tried the below code. It shows the undefined error on errbreadth and errheight when length field input is inccorect.

<?php
//get the data from form
$length = $_GET['length'];
$breadth=$_GET['breadth'];
$height=$_GET['height'];
//calculate volume and tsa
if($length <=0 || empty($length) || !is_numeric($length) ){
    $errlength = "You must enter valid length greater than zero";
    $volume = '';
    $tsa = '';

}
else if($breadth <=0 || empty($breadth) || !is_numeric($breadth) ){
    $errbreadth= "You must enter valid length greater than zero";
    $volume = '';
    $tsa = '';
}
else if($height <=0 || empty($height) || !is_numeric($height) ){
    $errheight = "You must enter valid length greater than zero";
    $volume = '';
    $tsa = '';
}
else{
$volume = $length*$breadth*$height;
$tsa = 2*($length*$breadth + $breadth*$height + $height*$length);
}
if(!empty($volume) || !empty($tsa))
{
    $errlength='';
    $errbreadth='';
    $errheight='';
}
     ?>


HTML>>
<html>
 <body>
     <form action = "cuboid.php" method= "get">
       Length<input type="text" name="length">
         Breadth<input type="text" name="breadth">
         Height<input type="text" name="height">
    <input type="submit" name="Volume" value="Volume">
         <input type="submit" name="TSA" value="TS">
     </form>
     <h1>Cuboid Volume Calculator</h1>
<label>Length: </label>
<span><?php echo $length?></span><span><?php echo $errlength?></span><br>
<label>Breadth: </label>
<span><?php echo $breadth?></span><span><?php echo $errbreadth?></span><br>
<label>Height: </label>
<span><?php echo $height?></span><span><?php echo $errheight?></span><br>
<label>Volume: </label>
<span><?php echo $volume?></span><br>
<label>Total Surface Area: </label>
<span><?php echo $tsa?></span><br>

 </body>
</html>

What's wrong with my code?

Uyur99
  • 35
  • 1
  • 8
  • the mistake is that you try to show `$errbreadth`, even if there is the chance that it isn't defined, simply because the is no error. So define $errlength on top of the script: `$errbreadth='';`. _OR_ only show it only when it is defined: `if(isset($errbreadth)) { echo $errbreadth; }` – Jeff Apr 02 '19 at 23:01
  • and this `if(!empty($volume) || !empty($tsa))` evaluates to _false_ if you have any error (and don't reach the `else`) - so having one error won't set the others to blank – Jeff Apr 02 '19 at 23:14

1 Answers1

0

There's a possibility $errlength,$errbreadth and $errheight are never set. You can get around this by adding the code below to the top of your PHP file:

$errlength='';
$errbreadth='';
$errheight='';

You may alternatively check if these variables are set, like how @Jeff commented above, but I personally am more comfortable when I know what type I am working with.

Hope this helps,

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33