PHP在数据库中导入CSV

PHP在数据库中导入CSV

本文介绍了如何使用Codeigniter PHP在数据库中导入CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用csv插入记录.我想将csv上传到我的应用程序,并想将其导入数据库中.现在,我有一个用户表,因此我想通过导入用户的csv文件来创建用户.我对文件上传了解得很少,但对于将其导入数据库却一无所知,请帮忙.

I am trying to insert records using csv. I want to upload csv to my Application and want to import it in database. Now I have a users table so i want to create users by importing user's csv file. I Know a little about file uploads but nil about importing it into database please help .

请参阅我使用以下命令完成了文件上传:控制器:

See I have done the file upload using :Controller:

       public function upload_csv()
      {
            $this->load->helper('form');
            $this->load->helper('url');

            //Set the message for the first time
            $data = array('msg' => "Upload File");

            $data['upload_data'] = '';

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

      }

另一个控制器的上载文件

The Another Controller Upload_file

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();

    }

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

}

和视图:

    <code>
    <?php if($upload_data != ''):?>
    <?php var_dump($upload_data);?>

    </code>
    <img scr="<?php echo $upload_data['full_path'];?>">
    <?php endif;?>

    <?php echo form_open_multipart('admin/upload_file/upload_it');?>

    <input type="file" name="userfile" size="20" />

    <br /><br />

    <input type="submit" value="upload" />

    </form>

现在如何将上载的文件导入数据库?

Now How do i import a uploaded file into my database ??

推荐答案

从2秒钟的Google到 PHP文档:

From a 2 second Google and the PHP docs:

$csv = array_map('str_getcsv', file('data.csv'));

然后您可以遍历数组和UPDATE您的数据库

Then you can loop through the Array and UPDATE your DB

这篇关于如何使用Codeigniter PHP在数据库中导入CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 14:27