Jump to content

Simple checkbox to database question


webref.eu

Recommended Posts

Hi All

 

I am creating a registration form that has a "Subscribe to Newsletter" checkbox on it.  If ticked, I want to record a value of 1 in my database, otherwise a value of 0.  This is the html in my form: 

 

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

 

Please could someone give me the code to get the desired values into the database. 

 

Many thanks

Link to comment
https://forums.phpfreaks.com/topic/116066-simple-checkbox-to-database-question/
Share on other sites

Thing with checkboxes is they are not passed if they are not checked. so you will have to put a check before you insert into the database

 

$SubscribeToNewsletter = isset($_POST['SubscribeToNewsletter']) ? "1" : "0";

 

Now if it is set $subscribeToNewletter will equal 1 if not is will be equal to 0;

 

Ray

 

When you use IF, you need two "==", not one.

 

<input type="checkbox" name="SubscribeToNewsletter" value="1"/>

 

<?php
$SubscribeToNewsletter = $_POST['SubscribeToNewsletter'];

if($SubscribeToNewsletter = "1"){
// mysql shit up in this bitchy, ya digg?
}

Thing with checkboxes is they are not passed if they are not checked. so you will have to put a check before you insert into the database

 

$SubscribeToNewsletter = isset($_POST['SubscribeToNewsletter']) ? "1" : "0";

 

Now if it is set $subscribeToNewletter will equal 1 if not is will be equal to 0;

 

Ray

 

 

well technically that doesn't matter.  if it's set it will equal 1. If it's not set, it won't be equal 1.  Therefore doing

<?php
$SubscribeToNewsletter = $_POST['SubscribeToNewsletter'];

if($SubscribeToNewsletter = "1"){
// mysql shit up in this bitchy, ya digg?
}

 

will work.  Well, aside from him needing == not =. 

 

Also, since the posted value already equals 1, why make a new variable assigning 1 or 0? Simply use the original var.  On the other hand, the posted var would need to be sanitized and your ternary inadvertently does that by assigning it 1 no matter what value was posted.

 

Thanks for your help everybody, just using:

 

<input type="checkbox" name="SubscribeToNewsletter" value="1" />

 

and later ...

 

$SubscribeToNewsletter = $_POST['SubscribeToNewsletter'];

 

is giving me the 0 value when not checked and the 1 when checked as I wanted. 

 

Thanks again.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.