1. 程式人生 > >上傳檔案並匯入資料庫

上傳檔案並匯入資料庫

選擇檔案上傳並匯入資料庫

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'.