Search code examples
phphtmlformsisset

PHP calculator width html form


can't figure out why my form will not work.

it has to calculate area of a rectangle. Form has to disappear after submit and show answer in a sentence.

php code has to check if form is filled and submitted, then hide it and echo the answer, I'm just learning, so sorry if it seems too easy of an issue.

<?php
if(isset($_POST['submit'])) {

if(!isset($_POST['length'], $_POST['width']))

{
  function area($a, $b) {
    $sum = $a * $b;
    echo "rectangle, with  $a cm in length and $b cm in width, area is $sum square cm.";}
    area($_POST['length'], $_POST['width']);  
} }

else { ?>
<form action="<?php $_PHP_SELF; ?>" method="POST">
        Length: <input type="text" name="length" />
        Width: <input type="text" name="width" />
        <input type="submit">
    </form>
<?php } ?>

Solution

  • You need $_SERVER['PHP_SELF'] instead of $_PHP_SELF to post to the current url. Or just leave it empty.

    Also the isset check is incorrect.

    With below code, it should work:

    <?php
    if (!empty($_POST)) {
        if (isset($_POST['length'], $_POST['width'])) {
            function area($a, $b)
            {
                $sum = $a * $b;
                echo "rectangle, with  $a cm in length and $b cm in width, area is $sum square cm.";
            }
    
            area($_POST['length'], $_POST['width']);
        }
    } else { ?>
        <form method="POST" enctype="multipart/form-data" action="">
            Length: <input type="text" name="length"/>
            Width: <input type="text" name="width"/>
            <input type="submit">
        </form>
    <?php } ?>