CodeIgniter Forums
How to properly save checkboxes in the DB - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: How to properly save checkboxes in the DB (/showthread.php?tid=22181)



How to properly save checkboxes in the DB - El Forum - 08-31-2009

[eluser]rvillalon[/eluser]
What's the proper way of saving checkboxes into a database?

In my database, I have a checkbox field that I set as NOT NULL tinyint(1)

I create the checkbox as follows:
$sale_option = array(
'name' => 'sale',
'id' => 'sale',
'value' => '1',
'checked' => FALSE,
);
<?php echo form_checkbox($sale_option); ?>

I validate it with:
$this->form_validation->set_rules('sale', 'On Sale', 'trim|xss_clean|integer');

But when I save it into the DB and it's unchecked, it gives me an error. I guess because it's NULL? Should I just make the field NULL instead of NOT NULL?


How to properly save checkboxes in the DB - El Forum - 08-31-2009

[eluser]rvillalon[/eluser]
I tweaked it a little to remove the error.

Before I send it out to the database, I do this:
$data_product['sale'] = ($this->form_validation->set_value('sale') == null) ? 0 : 1;

This works just fine, but is there a proper way of handling checkboxes?


How to properly save checkboxes in the DB - El Forum - 08-31-2009

[eluser]brianw1975[/eluser]
eh, to make the most of the server space I would suggest ENUM field with possible values of either 0/1 or Y/N

which ever you choose is up to you.

ENUM would limit you to just 2 choices where as tinyint can be from -127 to +127 or something like that so more unused data space is required for the field and for every record you have to increment that unused space.


How to properly save checkboxes in the DB - El Forum - 08-31-2009

[eluser]rvillalon[/eluser]
Thanks for the advice!