Jump to content

Unidentified index error in a simple form


Calamity-Clare

Recommended Posts

I have been trying to make an HTML form that is handled by a PHP script. So far my attempts to get it to work have proven fruitless.

 

I'm referencing the Visual Quickstart Guide for PHP to learn PHP, & I have since been referencing countless other websites & as far as I can tell, I shouldn't be getting any errors. I have written the code exactly the way it is in the book, yet when I enter values into the fields it returns a "Notice: Undefined index: title in /home/optionst/public_html/test.php on line 20" error message for all of the fields.

 

This is the code that I've written to handle the data in the form:

<?php

 

ini_set ('display_errors', 1);

error_reporting (E_ALL | E_STRICT);

 

$title = $_POST['title'];

$name = $_POST['name'];

$response = $_POST['response'];

$comments = $_POST['comments'];

 

print "Thank you, $title $name for your comments.";

print "You stated that you found this response to be $response and added: $comments ";

 

?>

Other than that, the only other text in the file is the html doctype, header & body tags. Line 20 is <$title = $_POST['title'];>

 

This is my html form:

<form method="post" action="test.php">

<p>Name: <select name="title">

<option value="Mr.">Mr.</option>

<option value="Mrs.">Mrs.</option>

<option value="Ms.">Ms.</option>

</select>

<input type="text" name="name" size="20" /></p>

 

<p>Email Address: <input type="text" name="email" size="20" /></p>

 

<p>Reponse: This is ...

<select name="response">

<option value="Excellent">Excellent</option>

<option value="Good">Good</option>

<option value="Boring">Boring</option>

</select>

 

<p>Comments: <textarea name="comments" rows="3" cols="30"></textarea></p>

 

<input type="submit" name="submit" value="Send My Feedback!" />

 

</form>

 

When I test the form, the "Notice: Undefined index: title in /home/optionst/public_html/test.php on line 20" appears for every field of the form. I have double checked that the values are all identical & that I put all the semi colons in. I can't think of anything else that would cause these errors.

 

Does anyone know why this would be happening?

Thanks

 

 

Link to comment
Share on other sites

These lines...

 

$title = $_POST['title'];
$response = $_POST['response'];

 

...will cause a Notice level error if the user doesn't select an item. Whilst some HTML elements will submit a value even if not filled in (<input type="text" /> for example), some don't. In order to avoid the error you need to check if(isset($_POST['title'])) before attempting to do anything with it.

Link to comment
Share on other sites

Ok, I follow you. I returned to my (less than) trusty book to see how to apply this & this is what I came up with:

<?php

 

ini_set ('display_errors', 1);

error_reporting (E_ALL | E_STRICT);

 

$title = $_POST['title'];

$name = $_POST['name'];

$response = $_POST['response'];

$comments = $_POST['comments'];

 

print "Thank you, $title $name for your comments.";

print "You stated that you found this response to be $response and added: $comments ";

 

$okay = TRUE;

 

if (empty($_POST['title']))

{print '<p class="error">Please specify your title.</p>';

$okay = FALSE;

}

 

if (empty($_POST['response']))

{print '<p class="error">Please indicate how you feel about this.</p>';

$okay = FALSE;

}

 

?>

 

I tried using isset in place of empty in the code & it didn't work, so I changed it to empty & the error messages I asked to print worked. This means it thinks the fields are empty, even though I have entered a value into every field, right?

 

I am on the right track, or way off?

Link to comment
Share on other sites

Your code is way off, You're checking if they exist after you call them.

 

if (isset($_POST['title']) && isset($_POST['name']) && isset($_POST['response']) && isset($_POST['comments']) {
$title = $_POST['title'];
$name = $_POST['name'];
$response = $_POST['response'];
$comments = $_POST['comments'];
} else { 
   die('One of the forms is empty, please hit back and re-enter.'); //Or create your own error system
}

print "Thank you, $title $name for your comments."; //Will only display if it is set.
print "You stated that you found this response to be $response and added: $comments ";

 

Or something similar, Easy enough.

Link to comment
Share on other sites

Your sort of on track, but not exactly. I'd recommend reading the manual for both isset and empty. Basically isset checks if a variable has been assigned a value. Whilst at first empty may appear to be the same thing it's not. As I mentioned previous if a text input is not filled in, the value of $_POST['name'] = ''; will be set. If you call isset or empty on that variable they will both return true because $_POST['name'] exists, and it is empty (a blank string). With a select element, if no value is selected then I don't believe a variable is returned at all, therefore using isset($_POST['title']) will return false, because there isn't an item in the array called title. The empty function will still return true, because of the way it works.

 

For a visual example of what I'm talking about, put this code at the top of your page and click submit at various stages of filling out the information and you'll see what I mean.

 

echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;

 

The same lines I previously mentioned will still throw Notice level errors because you are still attempting to assign $_POST['title'] to the variable $title, when there (potentially) isn't an item in the $_POST array under that name.

Link to comment
Share on other sites

oni-kun:

Thanks for your help :) Wouldn't have had a clue how to apply it myself, I have A LOT to learn!

 

cags:

Thanks for clarifying that. I think I get it lol. I guess what I'm finding the most confusing is that I'm getting error messages for "empty" fields, when I have entered a value into every one. I put that snippet of code into my script & half filled out the form & when I submitted the form all that printed on the screen was:

        Array (

        )

I tried using that before & it didn't print any of the variables then either.

 

So ... I guess my next question at this stage is how do I get the form to ignore empty fields? For the real form that I eventually create, there are only going to be a few compulsory fields. For the rest of the fields, it's up the form-filler-innerer as to whether or not they want to supply that information. Is there anyway I can get around these errors?

Link to comment
Share on other sites

I take it you did put that at the top of 'test.php' (or whatever page you actually have in your forms action attribute? The correct way to deal with unfilled fields in your case is to use...

 

if(isset($_POST['title']) {
   $title = $_POST['title'];
} else {
   $title = '';
}

 

After doing that you can safely use $title, because you know it will always have a value (albeit an empty string if the value wasn't selected). But the chances are you don't wish to allow blank values, so you will probably want the else statement to either send then back to the form with an error message or to log an error message then continue validating the data before returning to the form when fully validated. Here's an example of the way I like to perform validation. It's not perfect, you should theoretically filter the information before echo'ing it back to the user, but it should give you the idea.

 

<?php
if(isset($_POST['submit'])) {
   if(!isset($_POST['name']) || empty($_POST['name'])) {
      $error['name'] = "Name not filled in.";
   } elseif(preg_match("~[^a-z'`]~", $_POST['name'])) {
      $error['name'] = "Invalid characters used.";
   }

   if(!isset($_POST['email']) || empty($_POST['email'])) {
      $error['email'] = "You must fill in an e-mail address";
   }

   if(!isset($_POST['password'] || empty($_POST['password'])) {
      $error['password'] = "You must provide a password";
   }

   if(empty($error)) {
      // no errors with validation, proceed with whatever you wish to do with the data.
   }

}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<input type="text" name="name" value="<?php if(isset($_POST['name'])) { echo $_POST['name']; } ?>" />
<?php if(isset($error['name'])) { echo $error['name']; } ?><br/>
Email:
<input type="text" name="email" value="<?php if(isset($_POST['email'])) { echo $_POST['email']; } ?>" />
<?php if(isset($error['email'])) { echo $error['email']; } ?><br/>
Password:
<input type="text" name="password" value="<?php if(isset($_POST['password'])) { echo $_POST['password']; } ?>" />
<?php if(isset($error['password'])) { echo $error['password']; } ?>
<input type="submit" name="submit" />
</form>

Link to comment
Share on other sites

Hahaha oops, yeah I've just realised exactly why I don't want to bypass the validation of the form fields - if my form is stuck in a continuous loop of submitting blank fields then that's not going to help me in the slightest when I actually execute the form for my client's website. I need it to send emails & print variables to the screen & all sorts of weird & wonderful things which won't happen.

 

Thanks for sending that validation script & all the replies you've posted :) It's been really helpful. I've only just started out on php & I don't fully understand it all yet, so applying it in the right way is hard.

 

Guess I'm going to have to throw the question out to the rest of the forum! I'm not really a fan of vicious circles, zombie-styles brain-munching or otherwise, which is what my form's stuck in. I'm going to have to keep researching :)

 

The ultimate question to my life, my universe & my everything: Why does my form not recognise filled-in fields?

Link to comment
Share on other sites

Your code works fine providing you fill in all fields. With this block of code...

 

if (isset($_POST['title']) && isset($_POST['name']) && isset($_POST['response']) && isset($_POST['comments'])) {
    $title = $_POST['title'];
    $name = $_POST['name'];
    $response = $_POST['response'];
    $comments = $_POST['comments'];
} else {
    $title = '';
    $name = '';
    $response = '';
    $comments = '';
}

 

If all items are not filled in, they will ALL be blank.

Link to comment
Share on other sites

I'm guessing by your reply that you uploaded it to a server & tested it yourself? So it worked for you then?

 

It still won't work for me.

 

I've attached screenshots, Screenshot_TestHtml.jpg is of the test.html page, as you can see I've put a value in all of the fields & changed the drop down menus from its default option. Screenshot_TestPhp.jpg is what is displayed after I've submitted the form. As you can see it doesn't print any of the variables.

 

Is this what happened for you?

 

[attachment deleted by admin]

Link to comment
Share on other sites

Errrr lol ... I spoke too soon. I tried to apply it to the actual form I wanted, & I'm having the same problems. The test form is still working though. Hehehe It doesn't surprise me. This is going to sound amateur, but I'm going to try restsrting my computer, maybe that's what did it last time.

 

This is frustrating ...

Link to comment
Share on other sites

I knew it was an amateur idea!

 

So ... Back to square one with no fix for my problem ...

 

Cags, when you asked me if I could see anything other than the text I see in the browser in 'view source', on the test.php page all I saw was the html shell (doctype, html, head & body tags) and the line of text that I asked test.php to print to the screen. On the new form I tried applying the script to, it shows me the html shell, the error notices (formatted in html) & the lines of text to print.

 

Why do you ask that?

Link to comment
Share on other sites

Cags, when you asked me if I could see anything other than the text I see in the browser in 'view source', on the test.php page all I saw was the html shell (doctype, html, head & body tags) and the line of text that I asked test.php to print to the screen. On the new form I tried applying the script to, it shows me the html shell, the error notices (formatted in html) & the lines of text to print.

 

Why do you ask that?

If your server wasn't set-up correctly the PHP code would have been visible, which would explain why it wasn't processed.

 

The idea of restarting is not necessarily as amateur as you think, but it is the server that would need restarting. The code you uploaded works fine for me on localhost, do you have the files running live on a server so I can view what happens myself?

Link to comment
Share on other sites

Oh ok then, that makes sense. Unfortunately, I don't have my own server so it all needs to be processed remotely.

 

Sure, the 2 forms are at:

http://www.optionstradingaustralia.com.au/test.html

http://www.optionstradingaustralia.com.au/attendance.html

 

The first link is for the test script I originally made. The second is the one I tried to apply it to today.

 

:)

 

Link to comment
Share on other sites

Assuming your code is similar to what you posted earlier, ie.

 

if (isset($_POST['title']) && isset($_POST['name'])&& isset($_POST['response']) &&isset($_POST['comments'])) {
    $title = $_POST['title'];
    $name = $_POST['name'];
    $response = $_POST['response'];
    $comments = $_POST['comments'];
} else {
    $title = '';
    $name = '';
    $response = '';
    $comments = '';
}

 

The most likely problem is a typo. Since this code will only work if all values are set, if you have typed in one of the names incorrectly (or the right letters, but wrong case) then nothing will work. Can I see the contents of attendance.php?

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.