Welcome Guest, Not a member yet? Register   Sign In
How to properly save checkboxes in the DB
#1

[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?
#2

[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?
#3

[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.
#4

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




Theme © iAndrew 2016 - Forum software by © MyBB