# Solved: Undefined index



## skyhigh007 (Jun 17, 2004)

I created an check.php page that takes in users E-maill address.


```
<form action="check.php" method="post" >
              <input  type="text" name="email"  size="10" />
              <input  type="submit" value="submit" />
        </form>
```
On the same page, I want to store it into the database


```
<?php
	     $email=mysql_real_escape_string($_POST["email"]);
              echo "<center>$email</center>";
	     $shop->db->check_email($email);
  $insert = "INSERT INTO tbl_subscribe (cst_submail) VALUES ('$email')";
	$result = $shop->db->executeQuery($insert, "result");	
	    
	   ?>
```
and the ERROR is "Notice: Undefined index: email in C:\wamp\www\newer\check.php on line 60 "

The link 60 is: $email=mysql_real_escape_string($_POST["email"]);

Does anyone know why I got the undefined index?


----------



## MMJ (Oct 15, 2006)

That just means that it can't find the $_POST["email"] variable. "Notice" errors should not even appear, depending on your setup.

Are you sure the from is sending the data correctly?


----------



## skyhigh007 (Jun 17, 2004)

Even If I changed the PHP code to

```
<?php  $email=$_POST["email"];
              echo "<center>$email</center>";
           ?>
```
it still gives me the error. If I type in something in the input text box, the echo will print out what i typed in the box. However, if I just directly go to the check.php page, it gives me the undefined index error.


----------



## Mudley (Apr 7, 2008)

I assume you're getting the error upon first loading the page, and you're not even seeing the form.

you need to use some logic to control portions of the code.

wrap the form action with a condition.
i usually name my form submits, so

then for the condition, <? if(array_key_exists('form_submit',$_POST))

if the $_POST array doesn't exist, you shouldn't be trying to take action


----------



## skyhigh007 (Jun 17, 2004)

well, I load it to that page and it gives me the error. If I type something then it won't give me the error. I guess you are right, i will try it out.


----------



## MMJ (Oct 15, 2006)

skyhigh007 said:


> However, if I just directly go to the check.php page, it gives me the  undefined index error.


Exactly. Thats because the form data isn't sent; so $_POST["email"] isn't set.


----------



## skyhigh007 (Jun 17, 2004)

so I used

```
if(isset($_POST['email'])){
             }else{}
```
However, the footer.php that I included at the end of check.php wont show up because during the checking of the validation of the E-mail, I used php die or exit fuction if the E-mail is not correct or does not exists. so I guess it terminates everything ?


----------



## Mudley (Apr 7, 2008)

yes, they terminate the execution of the script.

take them out 

if all your trying to do is stop the form from displaying, wrap with a hide form condition

<? if(isset($hideForm)): ?>
...
<? endif; ?>


----------



## skyhigh007 (Jun 17, 2004)

well, its during the checking e-mail process and if there's an error in the input e-mail, then i want to display a message and stop the next checking step. I changed to Echo instead of die or exit, then every checking steps were excuted and prints outs a lot of messages. 
you cant used break in if statement right ? any alternatives?


----------



## tomdkat (May 6, 2006)

If I were you, I would put the form validation code in a function that you would call like this:

// Get submitted form data

$result = validateForm({pass form data or get it directly via _POST in function});

// Print footer and other page info 

Then, "validateForm()" would issue any messages that need to be displayed. If it encounters a problem, it simply returns an error code to the main script (the caller) and the main script can decide what to do, as appropriate. This way, the validation of the form data won't interfere with the mechanics of building and sending the complete HTML page to the browser.

Peace...


----------



## Mudley (Apr 7, 2008)

why not check all inputs at once?

here's usually how i go about form validation:
$errArr = array(); // empty array for holding error message

if(!isset($_POST['email']) || $_POST['email'] == '')
$err[] = "you must enter a valid email address";

if(!isset($_POST['name']) || $_POST['name'] == '')
$err[] = "you must enter a valid name";

// and then, after you've trapped all the inputs:
if(!count($errArr))
{
// your real form action goes here
$hideForm = true;
}
else {
// output errors
echo implode("
",$errArr);
}


----------



## tomdkat (May 6, 2006)

Mudley said:


> why not check all inputs at once?


I agree to a point but if he wanted to address each error individually, he's got to stop the checking and report the error.

Using your code as an example, if/else blocks will be required:

// Pseudo-code
if (not valid e-mail address)
report invalid e-mail address
else if (missing name)
report missing name
else if (some other problem)
report other problem

and so on. That's partially why I suggest putting that logic in a separate function. The details of _how_ the validation is neatly organized and won't impact the flow of the creation of the HTML page. If he used a function, the logic would look more like what you wrote:

validateForm() {
if (not valid e-mail address) {
err = not valid e-mail address;
return err;
}

if (missing name) {
err = missing name;
return err;
}

if (some other problem) {
err = some other problem;
return err;
}
return 0 (or success or whatever)
}

You get the idea.

Peace...


----------



## Mudley (Apr 7, 2008)

unless the validation depends on previous inputs, there's not really any point in halting validation upon the first error

in fact, its a big UI 'piss off' factor to do so


----------



## skyhigh007 (Jun 17, 2004)

Here's my function:

```
function check_email ($email){
           if ($email==""){
            die("Please type in your E-maill address");
         }elseif(strpos($email, "@" )<2 ){
            die("Please type in a correct E-mail address");
          }elseif(strpos(substr($email,strpos($email,"@")), ".") < 2){
           die("Please type in a correct E-mail address");
         }elseif( strlen($email) <7 ){
          die("Please type in a correct E-mail address");
        }elseif(ubstr_count ($email,"@") !=1 ){
          die("Please type in a correct E-mail address");
        }else {

            echo "Thank you for signing up our newsletter";
       }
  }
```
 The die function will terminate the checking once the error is found, so that it does not go on to the next checking. Die and exit terminates my include footer.php in the check.php page.


----------



## Mudley (Apr 7, 2008)

not a very functional function

function isemail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
}

if(!isemail($email))
echo "please enter a valid email";


----------



## tomdkat (May 6, 2006)

Mudley said:


> unless the validation depends on previous inputs, there's not really any point in halting validation upon the first error


Sure there is. If he wants to highlight or provide specific context for the field with error, identifiying the fields individually makes sense. If you highlight ALL of the problem areas at the same time, the user can get confused and that's not good either.



> in fact, its a big UI 'piss off' factor to do so


Fact or opinion?

Peace...


----------



## tomdkat (May 6, 2006)

skyhigh007 said:


> Here's my function:
> 
> ```
> function check_email ($email){
> ...


If the "check_email()" function is called by the main script, you don't need the call to "die()" and can simply return a return code to the main script. Then, the main script can do whatever is necessary, like call footer.php, to send the rest of the page to the browser for the user to see.

Peace...


----------



## Mudley (Apr 7, 2008)

tomdkat said:


> Sure there is. If he wants to highlight or provide specific context for the field with error, identifiying the fields individually makes sense. If you highlight ALL of the problem areas at the same time, the user can get confused and that's not good either.
> 
> Fact or opinion?
> 
> Peace...


the errors can still be identified individually. the code change for that is easy

fact, and common sense

picture this, you submit 10 pieces of data in a single form.
OOPS, the first piece of data isn't correct.
The form remembered all the rest of your input though - phew.
You fix the first piece, but OOPS, the 2nd input isn't formatted properly either. Apparently the developer wants dashes in the phone number field 
No prob, the form remembered my data. Add the dashes, submit again.
OOOPS I forgot to select something on this select box  Submit again.
OOOOOOPS phone number gets dashes, but the social security number doesn't.

Wouldn't it be awesome if i knew ALL the errors before submitting the form 5 times?


----------



## tomdkat (May 6, 2006)

Mudley said:


> Wouldn't it be awesome if i knew ALL the errors before submitting the form 5 times?


Sure it would, BUT given the fact the user didn't supply the required information, in the first place, that means:

The user didn't know which fields were required or the proper format for the information to be supplied in the fields. (shame on page designer)
The user didn't care enough to fill in the form with the proper data or tried to put "bogus" data in just to get the form submitted. (shame on the user)
Given the fact we're NOT doing client-side validation (which would be perfect for this kind of thing), all the "back and forth" can be frustrating. On the flip side, being presented a page with a perceived "tons" of errors displayed can either confuse or dishearten the user so they give up on the form and go elsewhere.

As for the issue of alerting the user of ALL errors at once being a "good UI design" in fact, where is the data backing this up? Or is this simply your opinion you're trying to position as being fact?

As for this being a "common sense" issue, "common sense" would also dictate eliminating unnecessary server traffic, but that's a separate issue.

In the end, it will be up to the form designer to determine which method of alerting the user of which form fields has problems is the best for the form being designed.

Peace...


----------



## skyhigh007 (Jun 17, 2004)

So the way I check for the validation of the E-mail is not efficient or is nota good way to check ?

The check_email() was called in the body section of check.php page and thats the only php code in the check.php with the exception of include footer.php at the bottom of the page.


```
<?php
	      if(isset($_POST['email'])){
	       $email=mysql_real_escape_string($_POST["email"]);
           echo "<center>$email</center>";
           $shop->db->check_email($email);
            }else{
	    echo "Please type in your E-mail address";
	}
?>
```
I don't know if return will work on this, but i will try


----------



## skyhigh007 (Jun 17, 2004)

Great, the return statement worked.


----------



## skyhigh007 (Jun 17, 2004)

Even thought the return method worked and the messages gets printed, but then everything gets stored into the database. So, I guess I will have to use die or exit .


----------



## tomdkat (May 6, 2006)

skyhigh007 said:


> Even thought the return method worked and the messages gets printed, but then everything gets stored into the database. So, I guess I will have to use die or exit .


Or, you will need to adjust the structure of your script to better accommodate return values from functions. 

I'm thinking you script would function something like this (pseudo-code below):

Get form data

$validForm = validateForm();
if ($validForm == "false") {
// output any necessary error related info
} else {
// do any proper processing of form data, including storing in database
}

Send the footer info to the browser
End the script

*******************************

And then validateForm() would look like this:

function validateForm() {
$validForm = "true";
if (isset($_POST['email'])) {
$validEntry = $shop->db->check_email($_POST['email']);
if ($validEntry != "true")
$validForm = "false";
}
// and something similar for the other fields

return $validForm;
}

function check_email($email) {
$validField = "true";
$email=mysql_real_escape_string($email);
echo "$email​";

// Do e-mail address check here
if (not valid e-mail address) {
echo "Please type in a valid e-mail address";
$validField = "false";
}

return $validField;
}

And so on.

Peace...


----------



## skyhigh007 (Jun 17, 2004)

Yea, I solved the problem in a similar way that you've posted. Thanks


----------

