如何使用codeigniter将csv文件数据导入mysql数据库?

时间:2017-08-01 09:02:30

标签: php codeigniter

controller:partner.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Partner extends CI_Controller 
{
    function __construct() 
    {
        parent :: __construct();
        $this->load->helper(array('form', 'url', 'captcha', 'email'));
    }

    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 = FCPATH."resources/imported_file/".$filename;
            $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)))
                {
                    $data = array(
                        'firstname' => $importdata[0],
                        'email' =>$importdata[1],
                        'phone' =>$importdata[2],
                        'uploaded_date' => date('d-m-y'),
                        'twelfth_year' => date('Y'),
                        'client' => $client[0]['client_id'],
                        'class' => $radio
                    );
                    $this->db->insert('students',$data);
                }                    
                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>');
            }
        }
    }

视图:

<form method="post" enctype="multipart/form-data">
    <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>

我有一个csv文件,我想将csv文件数据导入mysql数据库。但是当我上传csv文件并点击提交时,它会生成错误,如图所示。

enter image description here

那么,我该如何删除此错误?请帮帮我。

谢谢

3 个答案:

答案 0 :(得分:0)

你应该使用codeigniter文件上传库上传文件,然后使用phpexcel库导入csv文件。

答案 1 :(得分:0)

尝试使用此代码,您可以使用CodeIgniter的上传库上传文件,$ worksheet是一个数组,您的所有数据都存储在该数组中,只需打印工作表。

class Excelreader_controller extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->library('upload');
    }

    function uploadFile()
    {
        $config['upload_path'] = './upload/';
        $config['allowed_types'] = 'xls|csv';     

        $this->upload->initialize($config);
        if($this->upload->do_upload('uploadfile'))
        {
            $target_path = "upload/" . basename( $_FILES["uploadfile"]["name"]); 
            if(move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $target_path)) {
                $file=$_FILES["uploadfile"]["name"];
                $csv_file="upload/".$file;
                $worksheet=array();
                if (($getfile = fopen($csv_file, "r")) !== FALSE) 
                {
                    $worksheet[] = fgetcsv($getfile, 1000, ",");
                    while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) 
                    {
                        $worksheet[]=$data;

                    }
                }

            }
            else
            {
                echo "not uploaded";
            }
        }
        else
            echo $this->upload->display_errors();

    }
}

答案 2 :(得分:0)

  <?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Partner extends CI_Controller 
 {
 function __construct() 
 {
    parent :: __construct();
    $this->load->helper(array('form', 'url', 'captcha', 'email'));
    $this->load->library('upload');
    $this->load->database();
    $this->load->helper('file');
}

public function student()
{
    if(isset($_POST["submit"]))
    {

if($_FILES['file']['name'])
                                {
                                    $filename = explode(".", $_FILES['students_list']['name']);

        if($filename[1] == 'csv')
                                    {

                                         $fp = fopen($_FILES['file']['tmp_name'],'r') or die("can't open file");

                                        while($data = fgetcsv($fp,1024)) 
                                         {
                                            for ($i = 0, $j = count($data); $i < $j; $i++)
                                            {   $item['firstname']=$data[0];
                                                $item['email'] =  $data[1];
                                                $item['phone'] =  $data[2];

                                                $item['uploaded_date'] = $data[3];
                                                $item['twelfth_year'] = $data[4];
                                                $item['client'] =  $data[5];
                                                $item['class'] =  $data[6];
                                            }
                                        $data = array('firstname' => $item['firstname'],
                                                'email' => $item['email'],
                                                      'phone' => $item['phone'],
                                                      'uploaded_date' => $item['uploaded_date'],
                                                      'twelfth_year' => $item['twelfth_year'] ,
                                                      'client' => $item['client'] ,
                                                      'class' => $item['class'], 

                                        $data['crane_features']=$this->db->insert('students',$data);

                                        }

                                    echo "<script type='text/javascript'>alert('FILE UPLOADED SUCCESSFULLY')</script>";
                                    fclose($fp) or die("can't close file");
                                    $data['success']="success";
                                    return $data;


                                    }
                                    }

                                    else{
                                            echo "<script type='text/javascript'>alert('TRY UPLOADING *.csv FILE')</script>";
                                            $this->load->view('uploadcssview');
                                        }
                                }

                        }
                    }

查看文件

     <form action = "<?php echo site_url('Partner/student'); ?>" 
       method="post" enctype="multipart/form-data" >
          <center>
         <label>SELECT A CSV File:</label></center>

         <div class="form-group">
         <div class="col-md-3"></div>
         <div class="col-md-4"><br/>
         <input type="file" name="file" id="file"  />
         </div>
         <br/>
         </form>

            <div class="col-md-1">
           <input type="submit" name="submit" value="Import" class="btn btn-
         info" />
          </div>