0

I'm building a simple user registration and information update forms which have a lot of checkboxes with CodeIgniter. I store the values of checkboxes as 1 (if checked) and 0 (if not checked) in MySQL database under the tinyint(1) fields. So in user update form, I have to set default values which are return from these MySQL fields. On the other hand, the data shouldn't lost if the form validation isn't passed. Because of that, I need to use set_checkbox function of CI with third parameter, like this:

<input type="checkbox" name="my_field" value="1" <?php echo set_checkbox('my_field', '1', $returned_boolean_value); ?> >

But it doesn't work, because my MySQL query doesn't return boolean value for variable $returned_boolean_value. It returns 0 or 1 as a string. So the PHP query becomes something like this:

set_checkbox('my_field', '1', '1');

but it must be something like this:

set_checkbox('my_field', '1', TRUE);

My question is how can I set this third boolean parameter of set_checkbox with the data which is return from database?

I also looked throw the relevant questions, but found nothing about it. Any help would be appreciated. Thanks in advance.

4 Answers 4

3

Cast to boolean

<?php echo set_checkbox('my_field', '1', (boolean) $returned_boolean_value); ?> 
Sign up to request clarification or add additional context in comments.

Comments

1

Another option using C++ style if/else

set_checkbox('my_field', '1', $returned_boolean_value ? TRUE : FALSE);

Comments

0

You could use the good old double negation, or string comparison

http://codepad.org/Y7W0WWau

set_checkbox('my_field', '1', !! $string_0_or_1 );
set_checkbox('my_field', '1', $string_0_or_1 == '1' );

2 Comments

like mark shows you typecast the result, or try set the db fieldtype to boolean
Yes, that is the cleanest solution.
0
<?php echo set_checkbox('my_field', '1', (int) $returned_boolean_value); ?> 
<?php echo set_checkbox('my_field', '1', intval($returned_boolean_value)); ?> 
<?php echo set_checkbox('my_field', '1', (bool)$returned_boolean_value); ?> 
<?php echo set_checkbox('my_field', '1', $returned_boolean_value=='1'?true:false); ?> 

You can use one of the above...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.