Jump to content

Undefined Index Errors


mastermike707

Recommended Posts

A Simple example of this would be when using forms, the incorrect way:
[code]<?php

// get the users name:
$name = $_POST['name'];

// get the user age:
$age = $_POST['age'];

// display thier name and age:
if($name != "" && $age != "")
{
    echo "Hello {$name}, you are {$age}";
    echo "<br /><br />";
}

?>
<form action="" method="post">
  Name: <input type="text" name="name" /><br />
  Age:&nbsp; <input type="text" name="age" size="3" />
  <input type="submit" value="Display Message" />
</form>[/code]
When you first run that code you'll get to undefined index messages:
[quote]Notice: Undefined index: name in C:\server\www\test.php on line 4

Notice: Undefined index: age in C:\server\www\test.php on line 7[/quote]
Now the proper way:
[code]<?php

// check that form has been submitted:
if(isset($_POST['submit']))
{
    // now that form has been submitted we can work with form variables

    $errors = '';
   
    // check that form fields has been filled in:
    if(isset($_POST['name']) && !empty($_POST['name']))
    {
        $name = $_POST['name'];
    }
    else
    {
        $errors[] = 'You have not filled in the name field';
    }

    // check the age variable is numeric
    if(isset($_POST['age']) && is_numeric($_POST['age']))
    {
        $age = $_POST['age'];
    }
    else
    {
        $errors[] = 'You have not filled in the age field correctly';
    }

    // check there are no errors:
    if(is_array($errors))
    {
        echo "Please correct the following errors:\n<ul>";

        foreach($errors as $error)
        {
            echo "<li>{$error}</li>\n";
        }

        echo "</ul>\n";
    }
    else
    {
        echo "Hello {$name}, you are {$age}";
        echo "<br /><br />";
    }
}

?>
<form action="" method="post">
  Name: <input type="text" name="name" /><br />
  Age:&nbsp; <input type="text" name="age" size="3" />
  <input type="submit" name="submit" value="Display Message" />
</form>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.