【问题标题】:how to import data from csv file into the database?如何将csv文件中的数据导入数据库?
【发布时间】:2017-07-25 06:05:19
【问题描述】:

控制器:

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 文件导入数据库,但现在它不能工作。那么,我该怎么做呢?请帮帮我。

谢谢

【问题讨论】:

    标签: php codeigniter csv


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您需要在项目中添加库 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);
                          }
                      }
              }
          }
      

      【讨论】:

      • 显示无法加载请求的类:CSVReader
      • 你需要在library文件夹中加载csvReader库
      • 此示例帮助您逐行从 csv 文件中获取数据,在涉及列标题的第 1 行之后,您尝试获取其他行然后将它们插入数据库。
      • 我现在已经将 csvreader 库加载到库文件夹中,查询类似于 INSERT INTO students (name, email, phone, uploaded_date, session, client_id , class) VALUES (NULL, NULL, NULL, '25-07-17', '2017', '4', '11th') 并且它还显示以下错误严重性:警告消息:fopen(sample (1 ).csv):打开流失败:没有这样的文件或目录
      • 上面的代码是您需要获取存储在文件夹中的 csv 的示例... fopen 显示他们没有获得正确的获取路径。
      【解决方案3】:

      您可以使用 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/ 文件夹中,然后执行所需的操作。

      您必须在此 sn-p 中设置自己的文件夹方向和所需的 Codeigniter 语法。

      【讨论】:

      • @omkara 你的脚本有什么错误?!
      • 现在我没有任何错误,它显示成功消息但 csv 数据未显示在学生表中
      • @omkara 检查您的 resources/imported_file/ 文件夹权限并允许其写入。
      • @omkara 但我仍然为您提供使用 PHPexcel 库,您也可以在其他需要中使用它。
      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 2021-11-22
      • 2021-10-20
      • 2017-07-19
      • 1970-01-01
      相关资源
      最近更新 更多