文件上传导入数据库

strrchr查找指定字符在字符串中的最后一次出现,’.csv’ != strrchr($filename,’.’ 查找出.csv
mb_convert_encoding转换字符的编码,从gkb转到


mb_convert_encoding转换字符的编码,从gkb转到utf-8
move_uploaded_file将上传的文件移动到新的位置

$filename = mb_convert_encoding($filename, 'gbk','utf-8');
		$ret = move_uploaded_file($tmp, $filename);
		if(true === $ret){
			include 'read.php';
			write($filename);
			echo '导入完毕';
		}else{
			echo '上传失败';
		}
		exit;
	}

multipart/form-data完整的传递文件数据




	
	Document


	

fopen :r只读方式打开

function write($file){
if(!file_exists($file)){die('文件不存在');}
	
//fopen 打开文件
$fp = @fopen($file,'r');//r只读方式打开
if(false===$fp){die('打开文件失败');}

连接数据库

$conn = @new mysqli('localhost','root','','school');

if($conn->connect_error){
	die('连接数据库失败');
}
$conn->set_charset('utf8');
// $time1 = microtime(true);

$sql = "insert into student (id,no,name) values";

fgets 读取文件 if($i>0 && $i%10000==0) 如果数据太多就一万一万的插入

$i = 0;
//打开日志文件
$log = fopen('log.txt', 'w'); 
while($str = fgets($fp)){	//fgets 读取文件
	$encoding = mb_detect_encoding($str,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
	if($encoding != 'UTF-8'){
		$str = mb_convert_encoding($str, 'utf-8',$encoding);
	}
	$arr = explode(',', $str);//分割
	if($i>0 && $i%10000==0){
		$sql = rtrim($sql,',');
		$ret = $conn->query($sql);
		if($ret){
			fwrite($log, sprintf('成功写入%s行' . PHP_EOL,$conn->affected_rows));
		}else{
			fwrite($log, '写入失败' . PHP_EOL);
		}
		$sql = "insert into student (id,no,name) values";
	}
	$sql .= "(null,'{$arr[0]}','{$arr[1]}'),";
	// echo '
'; $i++; } if(!empty($sql)){ $sql = rtrim($sql,','); $ret = $conn->query($sql); if($ret){ fwrite($log, sprintf('成功写入%s行' . PHP_EOL,$conn->affected_rows)); }else{ fwrite($log, '写入失败' . PHP_EOL); } } $conn->close(); fclose($fp);//关闭文件 fclose($log); }

你可能感兴趣的:(文件上传导入数据库)