0

I am just experimenting with some php at the top of my page to process some form data. It seems to want me to declare the variable even though this does not exist as it will be passed when the form is submitted.

I am getting the following error Notice: Undefined index: mysubmit in /home/grsim/public_html/age1.php on line 3

   <?php
    $problem='';
       if($_POST['mysubmit']=="Submit Form"){
           if($_POST['age']==''){
               $problem="The form is blank";
       } else {
          // do something
          $myage = $_POST['age'];
          if($myage < 21){
              echo "you are a bit young for this";
          } else {
             echo "you are old enough";
          }
      }}

Any help would be appreciated as I have not had to declare variables before use. I am using a button with the name of mysubmit.

gavsim
  • 1
  • 3

3 Answers3

0

just change your if line to

if(isset($_POST['mysubmit']) && $_POST['mysubmit']=="Submit Form"){
Endacy
  • 229
  • 10
  • 16
0

Some servers are set to where it gives the undefined index error when the index you put in $_POST doesn't exist. So do if(isset($_POST['index']) && $_POST['index']=='whatever') { ... }:

   <?php
    $problem='';
       if(isset($_POST['mysubmit']) && $_POST['mysubmit']=="Submit Form"){
           if(isset($_POST['age']) && $_POST['age']==''){
               $problem="The form is blank";
       } else {
          // do something
          if(isset($_POST['age']) && $_POST['age'] < 21) { 
                echo "you are a bit young for this";
          } else {
             echo "you are old enough";
          }
      }}

This is configurable in the server's setup. It can be set to give you empty string instead of throwing this error.

developerwjk
  • 8,619
  • 2
  • 17
  • 33
  • thanks i used this example and it works fine - i was confused as i have code on other servers that do not throw this error -thanks for your help – gavsim Feb 12 '15 at 20:55
0

In first run your variable mysubmit is not set yet. So you have this message.

Try this code to solve the problem:

  $problem='';
  $my_submit = isset($_POST['mysubmit']) ? $_POST['mysubmit'] : false;
  $myage = isset($_POST['age']) ? $_POST['age'] : false; 

   if($my_submit == "Submit Form"){
       if(empty($myage){
           $problem="The form is blank";
   } else {
      // do something

      if($myage < 21){
          echo "you are a bit young for this";
      } else {
         echo "you are old enough";
      }
  }}
Maksim Tikhonov
  • 770
  • 6
  • 15