如果数据库中存在编码器,请选中复选框数组


codeigniter check checkbox array if exist in database

我有一个包含复选框数组的表单,我试图在数据库中检查是否存在某个复选框值,如果不存在,则将其插入数据库:

下面是我当前的代码:

视图页面:

<form action="<?php echo site_url('test/post_form')?>" method="post">  
<input type="text" name="full_name">
<input type="checkbox" name="subject[]" value="Algebra" > 
<input type="checkbox" name="subject[]" value="Trigonometry" > 
<input type="checkbox" name="subject[]" value="Geometry" > 
<input type="submit" name="submit"> 

Controller Page:

public function post_form()
{
$post_data = array(
'subject'=>$this->input->post('subject'),
'full_name'=>$this->input->post('full_name'),
);  
$this->load->model('subject_model');  
if($this->subject_model->check_subject($post_data)===true)  
 {  
  $this->session->set_flashdata('msg', 'Already Exist');  
  redirect('test/error_page');  
 }
else  
{  
  insert to database
}
}

Model Page:

public function check_subject($post_data=array())  
{
extract($post_data);  
foreach($post_data as $key=>$value)  
{  
$this->db->select('subject');
$this->db->where('subject',$value['subject']);
$this->db->where('full_name',$value['full_name']);
$this->db->from('subject_table');  
$query=$this->db->get();  
  if ($query->num_rows() > 0)  
  {
      return true;
  } 
  else  
  {
  return true;  
  }
}
示例场景:
  • 假设db中存在三角函数,
  • 如果我勾选了所有的复选框并提交,它仍然会插入三角学。
  • 但是如果数据库中存在代数,
  • ,我选中了所有的复选框,它说已经存在。
  • 看起来只检查第一个值是否重复。

我认为你必须在单独的数组中跟踪数据库中的受试者并返回结果,它可能看起来像这样你可以将其设置为True FALSE组合或其他任何适合你的东西

public function check_subject($post_data=array())  
{
extract($post_data); 
$subjects=array(); 
foreach($post_data as $key=>$value)  
  {  
$this->db->select('subject');
$this->db->where('subject',$value['subject']);
$this->db->where('full_name',$value['full_name']);
$this->db->from('subject_table');  
$query=$this->db->get();  
  if ($query->num_rows() > 0)  
      $subjects[$value['subject']]=true;
  else  
      $subjects[$value['subject']]=FALSE; 
  }
return $subjects;
}

实际上你的主题是作为一个数组发布的,所以你可以这样检查

public function check_subject($post_data=array())  
{
$val = " '". implode( "', '",$post_data['subject']) ."' " ;
$this->db->select('subject');
$this->db->where(" subject in {$val} ");
$this->db->where('full_name',$value['full_name']);
$this->db->from('subject_table');  
$query=$this->db->get();  
  if ($query->num_rows() > 0)  
  {
    return true;
  } 
  else  
  {
    return false;  
  }
}

检查一下,我想它会起作用