This is likely a basic question, but I want to get information from a form field that the user does not have to fill out.
$optional = ($_POST['optionalfield']);
I get an error "Undefined Index: optional"
This is probably because there is no value to field. What is the best way of handling this? I will put this into a mysql database, and I will be keeping track of statistics, so putting in placeholder value by initializing the variable beforehand didn't seem like the right thing to do.
Getting info from an optional form field
Moderator: General Moderators
Re: Getting info from an optional form field
It's not an error, it's a notice.
If you're going to be putting this in a database, you'll also want to validate and sanitize the form data first.
Code: Select all
$optional = (isset($_POST['optional'])) ? $_POST['optional'] : '';Re: Getting info from an optional form field
I will validate and sanitize, I just wanted to be clear on this first.
Although I am new to PHP, so I did not understand all of your syntax.
This code checks to see if the post array contains a value for optional (via isset), but then what does the the rest of the code do? I don't know what this does.
Thanks.
Although I am new to PHP, so I did not understand all of your syntax.
Code: Select all
$optional = (isset($_POST['optional'])) ? $_POST['optional'] : '';Code: Select all
$_POST['optional'] : ''Re: Getting info from an optional form field
It's a ternary operator. It's equivalent to writing:
Code: Select all
if (isset($_POST['optional']))
{
$optional = $_POST['optional'];
}
else
{
$optional = '';
}