CodeIgniter Forums
working with checkboxes - 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: working with checkboxes (/showthread.php?tid=37295)



working with checkboxes - El Forum - 01-05-2011

[eluser]black.Blank[/eluser]
I am currently working on checkboxes. How can i get the values of 3 checkboxes and store it in 3 different fields in database?

For example i have checkboxes named sample[] and values: sample1, sample2, and sample3. And on my database I have samp1(the field to store value for the first checkbox-sample1) and so on..

Thanks.


working with checkboxes - El Forum - 01-05-2011

[eluser]umefarooq[/eluser]
you have to check in array if value exist then save in specific database column php in_array function can help you to solve your problem

Code:
if(in_array("sample1",$sample))
   $data['sample1'] = "sample1";

if(in_array("sample2",$sample))
   $data['sample2'] = "sample2";

if(in_array("sample3",$sample))
   $data['sample3'] = "sample3";

or you can do with loop
foreach($sample as $v){
   if("sample1"==$v)
   $data['sample1'] = $v;

if("sample2"==$sample)
   $data['sample2'] = $v;

if("sample3" == $v)
   $data['sample3'] = $v;
}
hope will work for you


working with checkboxes - El Forum - 01-05-2011

[eluser]black.Blank[/eluser]
thanks umefarooq Smile
the first one worked for me Smile


working with checkboxes - El Forum - 01-05-2011

[eluser]black.Blank[/eluser]
is there any other way on how i can rewrite the following sample code?
Code:
if(in_array('sample1',$sample)
  $samp = 1;
  else if(!in_array('sample1',$sample)
  $samp = 0;

if(in_array('sample2',$sample)
  $samp2 = 1;
  else if(!in_array('sample2',$sample)
  $samp2 = 0;

if the checkbox is ticked, then the value for the corresponding field in the dbase will be 1 else 0.


working with checkboxes - El Forum - 01-05-2011

[eluser]umefarooq[/eluser]
yes you can do it little more fast

Code:
$spam = 0;
$spam2 = 0;

if(in_array('sample1',$sample)
  $samp = 1;

if(in_array('sample2',$sample)
$samp2 = 1;

by default value will be 0 if exit then it will be change.


working with checkboxes - El Forum - 01-05-2011

[eluser]black.Blank[/eluser]
aryt. thanks