簡體   English   中英

如何將數據從csv文件導入數據庫?

[英]how to import data from csv file into the database?

控制器:

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文件導入數據庫,但現在無法正常工作。 那么,我該怎么做呢? 請幫我。

謝謝

除非您有令人信服的理由執行代碼導入,否則建議您查看Pentaho( https://sourceforge.net/projects/pentaho/ ),該工具可以將數據從csv文件上傳到大多數流行的數據庫。

嘿,您需要在項目中添加庫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);
                    }
                }
        }
    }

您可以使用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語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM