上传文件并导入数据库

选择文件上传并导入数据库

file_put_contents — 将一个字符串写入文件
语法:int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

返回值:该函数将返回写入到文件内数据的字节数,失败时返回 FALSE 


fwrite — 写入文件(可安全用于二进制文件)
语法:int fwrite ( resource $handle , string $string [, int $length ] )

返回值:fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。

首先先创建一个PHP文件,代码如下:

<?php
if(isset($_FILES['file1'])){	
	if($_FILES['file1']['error'] !=0){
	    die('上传文件失败');
    }
   $tmp = $_FILES['file1']['tmp_name'];
   $filename = $_FILES['file1']['name'];
   if('.csv' != strrchr($filename,'.')){
   	die('请上传csv格式的文件');
   }
   $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;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<form name="form1" action="<?php echo $_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
	    <input type="hidden" name="MAX_FILE_SIZE" value="1024000">
		<input type="file" name="file1">
		<input type="submit" value="上传">
	</form>
</body>
</html>

引入read.php文件(上传文件之后,要将文件导入到数据库中)
代码如下:

<?php
function write($file){

	if(!file_exists($file)) die('文件不存在');

	$fp = @fopen($file,'r');
	if(false === $fp) die('打开文件失败');

	$conn = @new mysqli("localhost","root","","myschool");
	if($conn->connect_error){
		die('连接数据库失败');
	}
	//设置编码格式
	$conn->set_charset('utf8');

	$sql = "insert into student1 (id,no,name) values";
	$i=0;
	
	//打开日志文件
	$log = fopen('log.txt','w');
	while($str=fgets($fp)){
		$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,'w写入失败' . PHP_EOL);
			}
			$sql = "insert into student1 (id,no,name) values";
		}
		$sql .= "(null,'{$arr[0]}','{$arr[1]}'),";
		$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,'oo写入失败' . PHP_EOL);
			}
	}
	$conn->close();
	fclose($fp);//关闭文件
	fclose($log);
}

fopen — 打开文件或者 URL 

语法:resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen() 中 mode 的可能值列表 
'r'  只读方式打开,将文件指针指向文件头。  
'r+'  读写方式打开,将文件指针指向文件头。  
'w'  写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。  
'w+'  读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。  
'a'  写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。  
'a+'  读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。  
'x'  创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE ,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。  
'x+'  创建并以读写方式打开,其他的行为和 'x' 一样。  
'c'  Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock() ) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).  
'c+'  Open the file for reading and writing; otherwise it has the same behavior as 'c'.  

猜你喜欢

转载自blog.csdn.net/qq_43628350/article/details/84874705