[英]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.