Findlay Mack
Findlay Mack

Reputation: 25

how can i handle a checkbox value being sent from the form to the php

Trying to understand how to handle the values sent from a checkbox. Got the form on one page which accepts a name value email etc then also a "mailingList" checkbox value but im struggling to handle the set and unset values. The following code is the $_POST method from the form page.

    if (isset($_POST['register'])) {
    $email = trim($_POST['email']);
    $password = trim($_POST['pwd']);
    $retyped = trim($_POST['conf_pwd']);
     $firstname = trim($_POST['fname']);
     $lastname = trim($_POST['lname']);
     $company = trim($_POST['company']);
     $mailingList = $_POST['mailingListCheckbox'];
    require_once('./includes/register_user_pdo.inc.php');
    }

I currently have this if statement to try and set the value of "mailingListValue" to try and handle it correctly but it doesn't seem to work.

    if (!isset($mailingList)) {
    $mailingListValue = 0;
    }
    else {
    $mailingListValue = 1;
    }   

Any tips on the if statement or what im doing wrong would be much appreciated!Thanks for any help!

edit: form

<input name="mailingListCheckbox" type="checkbox" id="mailingListCheckbox" value="1" checked="checked">
<label for="mailingListCheckbox">Yes, I would like to receive alerts and updates from the MSF</label> 

Upvotes: 0

Views: 74

Answers (3)

Michael Coxon
Michael Coxon

Reputation: 5510

Use @Sean 's method above (in the question comments) and do the test in when set $mailingList or test if a real condition is set to $mailingList i.e...

if($mailingList == 1) {
    //do something
} else {
    // dont do something
}

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Just do everything in one:

$mailingListValue = isset($_POST['mailingListCheckbox']) ? 1 : 0;

Upvotes: 0

pes502
pes502

Reputation: 1587

Edit your PHP code

if ($mailingList == 1) {
$mailingListValue = 1;
}
else {
$mailingListValue = 0;
}   

If your checkbox is checked, the $mailingList value will be "1"

Upvotes: 3

Related Questions