【问题标题】:CodeIgniter batch insert into specific columnsCodeIgniter 批量插入特定列
【发布时间】:2015-10-02 14:06:09
【问题描述】:

我有一个 CodeIgniter 应用程序和一个 MySQL 表,其结构如下:

Table shortlisted_candidates
id int PRIMARY KEY AUTO INCREMENT,
candidate_no int NOT NULL,
written_marks int,
viva_marks int

我想在这个表中做insert_batch,但是数据只会插入到idcandidate_no列中。

我知道 Codeigniter Active Records 类为批量插入提供了$this->db->insert_batch() 函数,但它实际上是在整个表中插入数据,而我希望只将数据插入到特定的列中。如何在 CodeIgniter 中实现这一点?

请注意,id 是一个 AUTO INCREMENT,PRIMARY KEY 列。

我的控制器代码:

class Shortlisted_candidates extends MY_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('Shortlisted_candidate');
        $this->load->helper('url');
        $this->load->helper('html');
        $this->load->helper('form');
        $this->output->enable_profiler(false);
    }
    function add(){
        $data = array();
        if ($_POST) {

            $data['candidate_no'] = $this->input->post('candidate_no');
            $this->Shortlisted_candidate->add_candidate_to_shortlist($data);
            $this->session->set_flashdata('message', 'Data Successfully Added');
            redirect('shortlisted_candidates/add');
        }
    }
}

我的型号代码:

class Shortlisted_candidate extends CI_Model
{

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function add_candidate_to_shortlist($data){
        //Following code inserts data in ALL COLUMNS
        $this->db->insert_batch('shortlisted_candidates', $data);
        //How to write active record batch insert query for inserting data in only `id` and `candidate_no` column?
    }
}

【问题讨论】:

  • 那么错误或问题是什么?
  • 那么$data 的值在哪里??
  • @IdentityUnkn0wn 它只插入一行,$data['candidate_no'] = 0。
  • 在你的 if 条件下 echo $this->input->post('candidate_no');并检查您是否得到任何结果?
  • @IdentityUnkn0wn 不,我什么也没得到。

标签: php mysql codeigniter


【解决方案1】:

您需要修改以下控制器功能。

function add(){
    $data = array();
    if ($_POST) {

        $data[0]['candidate_no'] = $this->input->post('candidate_no');
        $this->Shortlisted_candidate->add_candidate_to_shortlist($data);
        $this->session->set_flashdata('message', 'Data Successfully Added');
        redirect('shortlisted_candidates/add');
    }
  }

除此之外,您还需要修改表架构,以便设置其他字段的默认值。

【讨论】:

    【解决方案2】:

    您可以定义要在其中插入批次的列。所以你必须让你的数组看起来像

    $data = array(
        array(
                'id' => $id,
                'candidate_no' => $candidate_no
        ),
        array(
                'id' => $id,
                'candidate_no' => $candidate_no
        )
    );
    
    //now in controller
    
     $this->Shortlisted_candidate->add_candidate_to_shortlist($data);
    

    这将只插入特定列,而不是整个表的列

    【讨论】:

      猜你喜欢
      • 2013-11-10
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      相关资源
      最近更新 更多