How do I import CSV to mysql using codeigniter

2019-03-31 07:48发布

问题:

I have a list of csv files, which I want to be import to mysql db, using codeigniter.

I tried $this->load->library('getcsv'); library but how to import the csv without uploading the CSV files to the server, what I meant was just uploading the files to a temp location like how pure coding PHP does.

Any idea?

Example:

I wanted something like this.

HTML:<input type="file" name="csv" />

to a temp string

Codeigniter: $this->input->upload['tmp_name']

回答1:

I gave exactly the answer for this. Take a look at this answer of mine for your problem's solution.

This will generate report in CSV format.

Reports in Codeigniter

And this will tell you how to read and dump csv files.

Codeigniter REST CSV import to mysql



回答2:

Try This:

Database:

SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `contacts`;
CREATE TABLE `contacts` (
  `contact_id` int(11) NOT NULL auto_increment,
  `contact_first` varchar(255) character set latin1 default NULL,
  `contact_last` varchar(255) character set latin1 default NULL,
  `contact_email` varchar(255) character set latin1 default NULL,
  PRIMARY KEY  (`contact_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

import.php::

<?php  

//connect to the database 
$connect = mysql_connect("localhost","username","password"); 
mysql_select_db("mydatabase",$connect); //select the table 
// 

if ($_FILES[csv][size] > 0) { 

    //get the csv file 
    $file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file,"r"); 

    //loop through the csv file and insert into database 
    do { 
        if ($data[0]) { 
            mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES 
                ( 
                    '".addslashes($data[0])."', 
                    '".addslashes($data[1])."', 
                    '".addslashes($data[2])."' 
                ) 
            "); 
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    // 

    //redirect 
    header('Location: import.php?success=1'); die; 

} 

?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<title>Import a CSV File with PHP & MySQL</title> 
</head> 

<body> 

<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?> 

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
  Choose your file: <br /> 
  <input name="csv" type="file" id="csv" /> 
  <input type="submit" name="Submit" value="Submit" /> 
</form> 

</body> 
</html> 

//get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file,"r");

    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            mysql_query("INSERT INTO contacts_tmp (contact_first, contact_last, contact_email) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."',
                    '".addslashes($data[2])."'
                )
            ");
        }
    } while ($data = fgetcsv($handle,1000,",","'"));
    //


回答3:

First change the default_controller value in route.php which lies inside config folder.

$route['default_controller'] = "csv";

Create a controller as csv.php

<?php
class csv extends CI_Controller
{
    public $data;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('csv_model');
    }
    function index()
    {
        $this->load->view('uploadCsvView',$data);
    }
    function uploadData()
    {
        $this->csv_model->uploadData();
        redirect('csv');
    }
}
?>

And create a model as csv_model.php

<?php
class csv_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    function uploadData()
    {
        $count=0;
        $fp = fopen($_FILES['userfile']['tmp_name'],'r') or die("can't open file");
        while($csv_line = fgetcsv($fp,1024))
        {
            $count++;
            if($count == 1)
            {
                continue;
            }//keep this if condition if you want to remove the first row
            for($i = 0, $j = count($csv_line); $i < $j; $i++)
            {
                $insert_csv = array();
                $insert_csv['id'] = $csv_line[0];//remove if you want to have primary key,
                $insert_csv['empName'] = $csv_line[1];
                $insert_csv['empAddress'] = $csv_line[2];

            }
            $i++;
            $data = array(
                'id' => $insert_csv['id'] ,
                'empName' => $insert_csv['empName'],
                'empAddress' => $insert_csv['empAddress'],
            $data['crane_features']=$this->db->insert('tableName', $data);
        }
        fclose($fp) or die("can't close file");
        $data['success']="success";
        return $data;
    }
}

And at last create a view as uploadCsvView.php

<form action="<?php echo site_url();?>csv/uploadData" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
    <table>
        <tr>
            <td> Choose your file: </td>
            <td>
                <input type="file" class="form-control" name="userfile" id="userfile"  align="center"/>
            </td>
            <td>
                <div class="col-lg-offset-3 col-lg-9">
                    <button type="submit" name="submit" class="btn btn-info">Save</button>
                </div>
            </td>
        </tr>
    </table> 
</form>

And create mysql table where data is going to be inserted:

CREATE TABLE tableName(
    id INT,
    empName VARCHAR( 100 ) ,
    empAddress VARCHAR( 100 ),
    PRIMARY KEY (id)
)

And most important point:

MySql and Csv file should both be same

Sample csv data is in the following link:

https://drive.google.com/file/d/0B-OuLrage4PpUmtKNkhuS1JrSkE/view?usp=sharing