2017-07-25 221 views
1

控制器:如何從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文件導入數據到數據庫,但現在它無法工作。那麼,我該怎麼做?請幫幫我。

謝謝

回答

0

除非你有一些令人信服的理由,在代碼執行導入,我建議你看看Pentaho的(https://sourceforge.net/projects/pentaho/),它可以從一個CSV文件中最流行的數據庫上傳數據。

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); 
        } 
       } 
     } 
    } 
+0

它顯示無法加載所請求的類:CSVReader – omkara

+0

您需要加載庫文件夾中的csvReader庫 – Madhur

+0

此示例可幫助您逐行獲取csv文件中的數據,並在涉及列標題的第1行之後嘗試獲取其他行然後將它們插入數據庫。 – Madhur

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)); 
        } 
       } 
      } 
    } 
?> 

此示例可以幫助您通過行和涉及列標題,第1行後,得到csv文件作爲行數據,你試圖讓其他行則將它們插入數據庫。

在腳本的頂部,我將文件保存在/ tmp /文件夾中,然後執行所需的操作。

您必須在此代碼段中設置自己的文件夾路線並需要Codeigniter語法。

+0

我的代碼有什麼問題請告訴我 – omkara

+0

@omkara您從腳本中得到了哪些錯誤?! –

+0

現在我沒有任何錯誤,它顯示成功味精,但csv數據不顯示在學生表 – omkara