carefulnow1
carefulnow1

Reputation: 841

How to check if a checkbox is ticked in PHP

OK so basically I have a HTML checkbox:

<input type="checkbox" name="mailinglist" />

This checkbox is on a user sign up form and this determines if they want to subscribe to the mailing list. I just want this the return as a 1 or 0 (boolean) inside the PHP. As you can see I am using POST:

<form action="process-create.php" method="POST">

And in my PHP it is receiving that post like this:

$mailinglist = $_POST['mailinglist'];

This all looks fine up to here. Now I want to input it into a database (with a boolean value). This is the code that inputs it into the database:

$data = array('username'=>$username, 'firstname'=>$firstname, 'lastname' => $lastname, 'mailing_list'=>$mailinglist, 'email'=>$email );
mysql_insert('users', $data);

Even when I tick the box it still says 0 in the databse. As you can see:

USERNAME       FIRSTNAME       LASTNAME       MAILING LIST       EMAIL
odixon         Oliver          Dixon          0                  *********

Any suggestions? If you want more samples of code I would be happy to give them (if it would help).

Upvotes: 1

Views: 392

Answers (3)

praveen
praveen

Reputation: 286

In your html page :

<input type="checkbox" name="mailinglist" value="1">

After submitting the form you can check it with:

isset($_POST['mailinglist'])
or
if ($_POST['mailinglist'] == '1')...

Upvotes: 0

Krish R
Krish R

Reputation: 22741

Can you try this,

 <input type="checkbox" name="mailinglist" value="yes"/>

 <?php  if(isset($_POST["mailinglist"]) && $_POST["mailinglist"]=="yes"){
             echo "checkbox ticked";
       }
 ?>

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137557

Instead of

$mailinglist = $_POST['mailinglist'];

I believe you want to use:

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

The name associated with the checkbox is included only if the checkbox is checked. Its value is the value of the checkbox (which you've omitted).

Upvotes: 1

Related Questions