如何使用 PHP CodeIgniter 将 CSV 数据导入 MYSQL 数据库?

How to import CSV Data into MYSQL database using PHP CodeIgniter?

您好,我已经看到了所有问题,但找不到适合我的问题的答案。答案是关于如何读取 csv 格式而不是导入到 MYSQL 数据库。

我有一个上传控制器,可以将我的文件上传到我的服务器上。现在我希望将上传的文件导入到 MYSQL 数据库中。请帮助我。

控制器文件:

public function upload_it() {
    //load the helper
    $this->load->helper('form');

    //Configure
    //set the path where the files uploaded will be copied. NOTE if using linux, set the folder to permission 777
    $config['upload_path'] = 'application/views/uploads/';

// set the filter image types
    $config['allowed_types'] = 'gif|csv';

    //load the upload library
    $this->load->library('upload', $config);

$this->upload->initialize($config);

$this->upload->set_allowed_types('*');

    $data['upload_data'] = '';

    //if not successful, set the error message
    if (!$this->upload->do_upload('userfile')) 
    {
        $data = array('msg' => $this->upload->display_errors());

    } 
    else
    { 

            //else, set the success message
            $data = array('msg' => "Upload success!");

            $data['upload_data'] = $this->upload->data();   

            if($_POST)
            {
                 if (($_FILES[csv][size] > 0 ) && ( $_FILES[csv][type]=="text/csv") ) 
                {
                        //get the csv file 
                        $file = $_FILES[csv][tmp_name]; 
                        $filetype=$_FILES[csv][type];
                        $handle = fopen($file, "r");
                        $i = 0;
                        $temp=str_getcsv($handle,"\n");
                        error_log("===$temp==");


                        $data = $this->user_m->('sip_id', 'sip_pass', 'name', 'key', 'email', 'password', 'phone', 'status', 'created', 'balance');


                        //Dont Know what to do next. 



                }

            }










    }

    //load the view/upload.php
    $this->load->view('admin/user/upload', $data);

}

现在我认为应该创建一个导入此上传文件的模型。但我不知道该怎么做

编辑:

我知道如何在 php 中执行此操作以连接到 mysql:

<?php 
$servername = "localhost"; 
$username = "username"; 
$password = "password"; 

// Create connection 
$conn = new mysqli($servername, $username, $password); 

// Check connection 
if ($conn->connect_error) { 
die("Connection failed: " . $conn->connect_error); 
} 
echo "Connected successfully"; 
?>

好的,正如你通过聊天告诉我的那样,你可以通过 exec 调用 php 文件,而 CI raw sql 对你来说是新的(相信我,我不会根本不知道CI )...

正如您所说的那样,文件名将从中获知,我们将其称为带有表单的 php 文件,并且该文件已经上传到 view某个已知层次结构中的文件夹,然后考虑以下字符串:

LOAD DATA INFILE '/full/path/to/view/myfile.txt' 
INTO TABLE users  
    FIELDS TERMINATED BY ',' 
           OPTIONALLY ENCLOSED BY '"'
    LINES  TERMINATED BY '\n'

是的,那将是 php 中的一大串。所以它将像任何其他字符串一样,如 select 语句。在你连接 mysqli 之后(正如你向我展示的那样,我编辑了问题),然后执行它!

如果进入 PHP $_POST 的文件名需要连接到上面的蓝色块中,那么这就是需要发生的事情。文件名后的单引号很重要,相信我。

来自 Load Data

的手册页