Checkboxes and PHP

I have a form on my website, but I have a problem passing the value of the checkbox.

I get the following error...

Notice: Undefined index: upgradeable in /var/www/vhosts/domain.com/httpdocs/***/includes/modules/admin.php on line 324 Unexpected error.

var_dump shows these errors...

Notice: Undefined index: upgradeable in /var/www/vhosts/domain.com/httpdocs/***/includes/modules/admin.php on line 325 NULL Notice: Undefined variable: upgradeable in /var/www/vhosts/domain.com/httpdocs/***/includes/modules/admin.php on line 327 Unexpected error.

My checkbox looks like this...

<input type="checkbox" name="upgradeable" class="" value="<?php echo $membership['upgradeable']; ?>" >

On admin.php line 324, looks like this...

$upgradeable = inputFilter($_POST['upgradeable']);

Can anyone please help me find the error.

Upvotes: 1

Views: 236

Answers (5)

Cups
Cups

Reputation: 6896

If a checkbox is not selected, nothing gets passed back to your form handler.

So use

if (isset($_POST['upgradeable'])){  // now sanitize }

Upvotes: 0

rrehbein
rrehbein

Reputation: 4160

If the checkbox is unchecked, then it won't be in $_POST

You'll need to use isset($_POST['upgradeable']) before using it, possibly setting it to a false value if it is not set.

Upvotes: 0

Amber
Amber

Reputation: 526543

Use something like isset() to check and see if the $_POST array actually contains a value for a given key before trying to access it. Unchecked checkboxes are never actually passed as POST parameters, and thus the key won't exist if the box isn't checked. So in fact, you can simplify your code:

$upgradeable = isset($_POST['upgradeable']);

(And then you'll get a TRUE/FALSE value in $upgradeable corresponding to checked/unchecked.)

Upvotes: 1

animuson
animuson

Reputation: 54719

The values of a checkbox are only sent if the checkbox is actually set to checked. If it is not checked, then the value is not set at all, so $_POST['upgradable'] will be undefined.

Try this:

$upgradeable = isset($_POST['upgradeable']) ? inputFilter($_POST['upgradeable']) : '';

Upvotes: 1

Alex Howansky
Alex Howansky

Reputation: 53533

If I'm not mistaken, when the checkbox is unchecked, you'll get nothing at all in the _POST array. (Versus "upgradable=on" when it is checked.) So if you want to avoid the warning, you can simply do:

if (isset($_POST['upgradable']) && $_POST['upgradable'] === 'on') ...

Upvotes: 0

Related Questions