-4

I would like to capture values from the input , calculate and display the result on the same page, but for some reason I keep getting this error:

Notice: Undefined index: inputval in C:\xampp\htdocs\php\exercise 2\exercise2-3.php on line 67

here is what I have done so far.A user enters 2+ 3 or 5 * 4 or 5-4 etc.

<div class="div">
    <h1>My Calculator</h1>
    <form method="POST">
    <?php

    echo "      <input type='text' name='inputval' size='15' class='inputs' /><input class='button' type='submit' name='register' value='Register'>
    </form>
    <p>";

        $string =$_POST["inputval"];
        $value = eval($string);

        echo "Result is:".$value;

        ?>
    </p>
</div>
Phil
  • 157,677
  • 23
  • 242
  • 245
Navy
  • 21
  • 1
  • 9

1 Answers1

1
<div class="div">
<h1>My Calculator</h1>
<form action="" method="POST">

<input type="text" name="inputval" size="15" class="inputs">
<input class="button" type="submit" name="register" value="Register">
</form>
<p>
    <?php
    if (!empty($_POST['inputval'])) {
        $string = $_POST['inputval'];
        $value = eval($string);

        echo 'Result is: ' . $value;
    }
    ?>
</p>

Start the php tag later on after your input tag's instead of echo'ing them in your php script. And check for input, else the code will still run even when there is no POST.

empty() will check if the array == false (if no values) or it is not set !isset().

!empty() will run when the value inside is not false or if values are set in the array.

Akshay Kalose
  • 787
  • 1
  • 5
  • 15