-1

I am trying to understand why one method of implementation produces (all the code in a .php file) - Notice: Undefined index:

and putting the same php code snippet into a separate action file and calling it from html does not.

See example code:

File that has an error - php_examp1.php

<!DOCTYPE html>
<html>
    <body>
    <p>Example</p>
        <form method="post">
          <label for="num1"> 1st Number (between 1 and 100):</label>
          <input type="number" id="num1" name="num1" min="1" max="100" step="0.01">
          <input type="submit" value="Submit">
        </form>
        The number entered is:  <?php echo $_POST["num1"]; ?><br>
    </body>
</html>

Files that do not cause an error -php_examp1.html

<!DOCTYPE html>
<html>
    <body>
    <p>Example</p>
        <form action = "action_examp.php" method="post">
          <label for="num1"> 1st Number (between 1 and 100):</label>
          <input type="number" id="num1" name="num1" min="1" max="100" step="0.01"> 
          <input type="submit" value="Submit">
        </form>
    </body>
</html>

File - action_examp.php

The number entered is:  <?php echo $_POST["num1"]; ?><br>
Jonn Mc
  • 15
  • 1
  • 7
  • 1
    if you call the first example for the first time, there is no post been made... – Honk der Hase Feb 25 '21 at 16:31
  • 1
    Because when you first open the page, nothing is posted (it's a simple `GET` request). If you directly open `action_examp.php` from the example #2, you'll get the same issue. – El_Vanja Feb 25 '21 at 16:31
  • 1
    Just as a quick solution - `echo $_POST["num1"] ?? 'Nothing entered';` – Nigel Ren Feb 25 '21 at 16:33

1 Answers1

0
<!DOCTYPE html>
<html>
    <body>
    <p>Example</p>
        <form method="post">
          <label for="num1"> 1st Number (between 1 and 100):</label>
          <input type="number" id="num1" name="num1" min="1" max="100" step="0.01">
          <input type="submit" value="Submit">
        </form>
        The number entered is:  <?php 
            if(array_key_exists('num1', $_POST)) {
                echo $_POST["num1"]; 
            }
        ?><br>
    </body>
</html>
Alex
  • 255
  • 2
  • 6