Getting info from an optional form field

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Markto
Forum Newbie
Posts: 22
Joined: Thu Nov 17, 2011 1:13 pm

Getting info from an optional form field

Post by Markto »

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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Getting info from an optional form field

Post by Celauran »

It's not an error, it's a notice.

Code: Select all

$optional = (isset($_POST['optional'])) ? $_POST['optional'] : '';
If you're going to be putting this in a database, you'll also want to validate and sanitize the form data first.
Markto
Forum Newbie
Posts: 22
Joined: Thu Nov 17, 2011 1:13 pm

Re: Getting info from an optional form field

Post by Markto »

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.

Code: Select all

$optional = (isset($_POST['optional'])) ? $_POST['optional'] : '';
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.

Code: Select all

 $_POST['optional'] : ''
Thanks.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Getting info from an optional form field

Post by Celauran »

It's a ternary operator. It's equivalent to writing:

Code: Select all

if (isset($_POST['optional']))
{
    $optional = $_POST['optional'];
}
else
{
    $optional = '';
}
Markto
Forum Newbie
Posts: 22
Joined: Thu Nov 17, 2011 1:13 pm

Re: Getting info from an optional form field

Post by Markto »

Thanks.
Post Reply