繁体   English   中英

如果数据库中存在codeigniter复选框数组

[英]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"> 

控制器页面:

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
}
}

型号页面:

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中存在三角函数,
  • 如果我选中所有复选框并提交,它仍然会插入三角函数。
  • 但是,如果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;  
  }

}

检查一下,我认为它将起作用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM