如何将数据从csv文件导入数据库?

时间:2017-07-25 06:05:20

标签: php codeigniter csv

控制器:

public function student()
{
    if($this->input->post('save'))
    {
        $client_id[0]['client_id'] = $this->session->userdata('client_id');
        $radio = $this->input->post('class');
        $client = $client_id[0]['client_id'];


        $filename = $_FILES['students_list']['name'];
        $path = base_url()."resources/imported_file/".$filename;
        $path = FCPATH."resources/imported_file/";
        $move=move_uploaded_file($_FILES['students_list']['tmp_name'],$path.$_FILES['students_list']['name']);
        if($_FILES["students_list"]["size"] > 0)
        {
            $file = fopen($path, "r");
            while (($importdata = fgetcsv($file, 10000, ",")) !== FALSE)
            {
                $data = array(
                    'name' => $importdata[0],
                    'email' =>$importdata[1],
                    'phone' =>$importdata[2],
                    'uploaded_date' => date('d-m-y'),
                    'session' => date('Y'),
                    'client_id' => $client[0]['client_id'],
                    'class' => $radio
                );
                $this->partner_model->insertCSV($data);
                echo $this->db->last_query();
            }                    
            fclose($file);
            $this->session->set_flashdata('err_csv', '<p style="color: #87b87f;font-weight: bold;text-align:center;">Data are imported successfully..</p>');
        }
        else
        {
            $this->session->set_flashdata('err_csv', '<p style="color: red;font-weight: bold;text-align:center;">Something went wrong..</p>');
        }
    }
}

观点:

<?php echo $this->session->flashdata('err_csv')?>
<form class="form-horizontal" method="post" role="form" enctype="multipart/form-data">
    <input type="radio" name="class" value="11th"/><b>XI</b>
    <input type="radio" name="class" value="12th Appearing"/><b>XII Appearing</b>
    <input type="radio" name="class" value="12th Passed"/><b>XII Passed</b>
    <input type="file"  id="students_list"  name="students_list" accept=".csv" class="required">
    <input type="submit" name="save" id="save" value="save" class="btn btn-info" />
</form>

模型:

<?php  
   class Partner_model extends CI_Model  
   {  
      function __construct()  
      {   
        parent::__construct();  
      }  
      public function insertCSV($data)
      {
         $this->db->insert('students', $data);
         return TRUE;
      }
   }  

在这段代码中,我有一个名为student_list的输入,我只上传csv文件。现在,我想将数据从csv文件导入数据库,但现在它无法工作。那么,我该怎么办呢?请帮帮我。

谢谢

3 个答案:

答案 0 :(得分:0)

除非你有一些令人信服的理由在代码中执行导入,否则我建议你看看Pentaho(https://sourceforge.net/projects/pentaho/),它可以将数据从csv文件上传到最流行的数据库。

答案 1 :(得分:0)

嘿,你需要在你的项目中添加库csvReader并使用下面的代码来设置这有助于你批次

public function student(){          
    $this->load->library('CSVReader');
     if (isset($_FILES['csv'])) 
        {
          if($_FILES["csv"]["error"] > 0) 
            {     //if there was an error uploading the file
                $this->session->set_flashdata('bulkUploadError', 'Invalid CSV File.');
                redirect('/');
            }
            //Store file in directory "upload" with the name of "uploaded_file.txt"
            $storagename = "csv" . date('m-d-Y') . ".xls";
            move_uploaded_file($_FILES["csv"]["tmp_name"], realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename);
            if ($file = fopen(realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename, 'r+')) 
                {
                    $result =   $this->csvreader->parse_file('uploads/' . $storagename);
                    $finalResult = $array = array_values(array_filter($result));
                    $this->data['worksheet'] = $finalResult;

                    foreach ($this->data['worksheet'] AS $key => $val) 
                    {

                            $data['id'] = $val['table field name'];
                            $this->common->save('table_name',$data);
                    }
                }
        }
    }

答案 2 :(得分:0)

您可以使用PHPExcel获取数据并将其插入数据库:

https://github.com/PHPOffice/PHPExcel

<?php
    $target_dir = "/tmp/";
    $target_file = $target_dir . basename($_FILES["students_list"]["name"]);
    $FileType = pathinfo($target_file,PATHINFO_EXTENSION);
    $filename = $_FILES["students_list"]["name"];
    if (isset($_FILES["students_list"])) {
            if($FileType == "csv" ) {
                if (move_uploaded_file($_FILES["students_list"]["tmp_name"], $target_file)) {

                    $target_file = $target_dir . $filename;

                    set_include_path(get_include_path() . PATH_SEPARATOR . 'resources/imported_file/');
                    include 'PHPExcel/IOFactory.php';

                    try {
                        $objPHPExcel = PHPExcel_IOFactory::load($target_file);
                    } catch(Exception $e) {
                        die('Error loading file "'.pathinfo($filename,PATHINFO_BASENAME).'": '.$e->getMessage());
                    }

                    $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                    $arrayCount = count($allDataInSheet);  // Here get total count of row in that Excel sheet


                    for($i=2;$i<=$arrayCount;$i++){

                        $name = trim($allDataInSheet[$i]["A"]);
                        $email = trim($allDataInSheet[$i]["B"]);
                        $phone = trim($allDataInSheet[$i]["C"]);
                        $uploaded_date = trim($allDataInSheet[$i]["D"]);
                        $session = trim($allDataInSheet[$i]["E"]);
                        $client_id = trim($allDataInSheet[$i]["F"]);
                        $class = trim($allDataInSheet[$i]["G"]);

                            $insert = $db->Queryinsert("students",array('',$name,$email,$phone,$uploaded_date,$session,$client_id,$class));
                    }
                }
            }
    }
?>

此示例可帮助您逐行从csv文件获取数据,在第1行之后涉及列标题,您尝试获取其他行,然后将其插入数据库。

在脚本的顶部,我将文件保存在/ tmp /文件夹中,然后执行所需的操作。

您必须在此代码段中设置自己的文件夹说明和所需的Codeigniter语法。