【问题标题】:Upload Excel Codeigniter Error double primary key上传 Excel Codeigniter 错误双主键
【发布时间】:2015-05-16 00:18:47
【问题描述】:

我想用 codeigniter 从 Excel 中插入数据,但我发现有些困难。当我上传文件时,主键中有一些数据双倍。我尝试在上传之前先检查一下

$cek=$this->m_admin->get_redudant($data['cells'][$i][2]);
if ($cek==0) {
    $this->m_admin->add($dataexcel);
    redirect('home','refresh');
}
else{
    echo "something wrong";
}  

这里是函数上传文件:

function do_upload(){
    $config['upload_path'] = './temp_upload/';
    $config['allowed_types'] = 'xls';           
    $this->load->library('upload', $config);                
    if ( ! $this->upload->do_upload())
    {
        $data = array('error' => $this->upload->display_errors());          
    }
    else
    {
        $data = array('error' => false);
        $upload_data = $this->upload->data();

        $this->load->library('excel_reader');
        $this->excel_reader->setOutputEncoding('CP1251');

        $file =  $upload_data['full_path'];
        $this->excel_reader->read($file);
        error_reporting(E_ALL ^ E_NOTICE);

        $data = $this->excel_reader->sheets[0] ;
        $dataexcel = Array();
        $i=0;
        for ($i = 1; $i <= $data['numRows']; $i++) {
                        if($data['cells'][$i][1] == '') break;
                        $dataexcel[$i-1]['nip'] = $data['cells'][$i][2];
                        $dataexcel[$i-1]['nama'] = $data['cells'][$i][1];
                        $dataexcel[$i-1]['nipbr'] = $data['cells'][$i][3];
                        $dataexcel[$i-1]['tempat'] = $data['cells'][$i][4];
                        $dataexcel[$i-1]['lahir'] = $data['cells'][$i][5];
                        $dataexcel[$i-1]['temp_kerja'] = $data['cells'][$i][6];
        }

        delete_files($upload_data['file_path']);            
        $cek=$this->m_admin->get_redudant($data['cells'][$i][2]);


        if ($cek==0) {
            $this->m_admin->add($dataexcel);
            redirect('home','refresh');
        }
        else{
            echo "something wrong";
        }    
    }

}

我想在主键中操作数据。如果数据存在,我会在 id 的末尾随机添加数据,比如

else{
        $x = rand(1, 1000); 
        $dataexcel[$i-1]['nip'] = $data['cells'][$i][2]."$x";
} 

但是不行,我该怎么办..

【问题讨论】:

    标签: php mysql excel codeigniter


    【解决方案1】:

    在这行代码中:

    $x = rand(1, 1000); 
    

    如果数据存在,您可以定义一个全局计数器和增量:

    else{
        $counter+=1; 
        $dataexcel[$i-1]['nip'] = (int)$data['cells'][$i][2].$counter;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 2015-09-27
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多