如何使用codeigniter将复选框值写入数据库,使其为1/0而不是on/0


how to write checkbox value to database as 1/0 instead of on/0 with codeigniter

尝试在我的数据库中保存复选框的选中状态。我正在使用代码点火器。我将cehckbox形式值添加到数组中,如下所示:'treated' => $this->input->post('treated'.$i),

然后,我通过包含上述输入的数组写入数据库。

这将作为"on"写入数据库,并与char/varchar一起使用。但是,如果我将其更改为bittinyint(1),它将失败,并出现mssql错误Conversion failed when converting the varchar value 'on' to data type tinyint.

如何将选中的复选框值传递为1而不是on

提前谢谢。

更新

 $i=1;
    while($i<=$this->input->post('orderlines'))
  {
$treatedVal=$this->input->post('treated'.$i)?1:0;
      //set the data for line insert start
        $data = array(
      'treated' => $treatedVal,    
        );
        $this->sales_model->order_lines_insert($data);  
  $i++;
  }

您应该在HTML本身中更改它。

<html>
    <input type="checkbox" name="check" value="1" />  <!--give it a value attribute the default is "on"-->
</html>

只需在创建数据数组之前执行此操作

 $treatedVal=$this->input->post('treated'.$i)?1:0;
 // then add this variable value to your array
 'treated' => $treatedVal,

我就是这样做的:

var myVal = ( $('#myCheckbox').is(':checked') ) ? 1 : 0;
alert('myVal is: ' +myVal); //alerts 1 if checked, 0 if not checked

jsFiddle演示