0
<html>
<body>
  <form action="" method="GET">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form> 
</body>
</html>
<?php
  if( $_GET["name"] || $_GET["age"] )
  {
     echo "Welcome ". $_GET['name']. "<br />";
     echo "You are ". $_GET['age']. " years old.";
  }
?>

Question:

when I open above script in browser, It shows:Notice: Undefined index: name in D:\wamp\www\oop\test3.php on line 13, I know if is because the form is not submit yet, so $_GET["name"] does not exist, but how to fix this problem?

user2580076
  • 577
  • 2
  • 10
user2294256
  • 1,029
  • 1
  • 13
  • 22
  • possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – kittycat Jul 20 '13 at 03:59

4 Answers4

1

Just set the name of the submit button, and use isset() to check if the form was submitted.

<html>
    <body>
      <form action="" method="GET">
          Name: <input type="text" name="name" />
          Age: <input type="text" name="age" />
          <input type="submit" name="submit" />
      </form> 
    </body>
</html>

<?php
    if( isset($_GET['submit']) )
    {
        echo "Welcome ". $_GET['name']. "<br />";
        echo "You are ". $_GET['age']. " years old.";
    }
?>
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
1

The example below will check if both fields are filled.

If one or the other is not filled, an error message will appear.

If both are filled, then the user will see:

Welcome Bob // assuming the person's name is "Bob" in the field.
You are 30 years old. // assuming the person entered "30" in the field.

Otherwise, it will echo:

Fill in all fields.

Here is the example below:

<html>
    <body>
      <form action="" method="GET">
          Name: <input type="text" name="name" />
          Age: <input type="text" name="age" />
          <input type="submit" name="submit" />
      </form> 
    </body>
</html>

<?php


if($_GET['name'] && $_GET['age'])

    {
        echo "Welcome ". $_GET['name']. "<br />";
        echo "You are ". $_GET['age']. " years old.";
    }

if(!$_GET['name'] || !$_GET['age'])

    {

        echo "Fill in all fields";

    }

?>

I've made use of both && and || logical operators for validation.

Consult the PHP manual for more information: http://php.net/manual/en/language.operators.logical.php

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

You can test if your particular _GET variable exists. For example:

<?php
if ( isset ( $_GET["name"] ) ) {
    echo "Welcome ". $_GET['name']. "<br />";          
}
?>
Ryan
  • 26,884
  • 9
  • 56
  • 83
-1

Try:

<form action="" method="GET">
Name: <input type="text" name="name" id="name" />
Age: <input type="text" name="age" id="age" />
<input type="submit" />
</form>
Ricky Nelson
  • 876
  • 10
  • 24