关闭

PHP实现客户端将CSV文件导入服务器数据库中

标签: csv服务器php数据库fileimport
820人阅读 评论(0) 收藏 举报
分类:

//将文件另存为php文件,在服务器上运行,已测试通过。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 <title>Import CSV file to server</title>
</head> 
<body>   
    <form id="form1" name="form1" enctype="multipart/form-data" method="post" action="importcsv.php">
  <input type="file" name="upfile" size="20" />
  <input type="submit" name="Submit" value="Import" />[*.CSV]
 </form>
</body>
</html>
<?php
//*****************************************************************
//function:      import local CSV file to one table of database in server
//solve way:    copy local CSV file to server ,get the data from CSV file
//                   line by line ,then insert them into the table of database,
//                   at last,delete the file in server.
//author:       enjoyxp 2007-09-20
//******************************************************************

if($_POST['Submit']=='Import'){
    $type='application/vnd.ms-excel';        //set valid file type
 $file=$_FILES['upfile'];                 //get file
 copy($file['tmp_name'],$file['name']);      //copy local file to server
 $filename=$_FILES['upfile']['name']; 
 $handle = fopen("$filename","r");           //open file
 if($_FILES['upfile']['type']!=$type){
     echo "<script>alert('Error:file type doesn't match!');</script>";
  fclose($handle);                        //close file
  unlink($filename);                      //delete file
     exit;
    }
 $i=0;
 while ($data = fgetcsv($handle,1000,",")){ //read file line by line,each line explode by ','
  $i++;
     $num = count($data);                   //how many lines the file has
     $flag = false;
  for($n=0; $n < $num; $n++){      //judge each line whether is null
     if($data[$n] !=''){
    $flag = true;                     //if $null equal true,then  exist data
    break 1;                          //jump out of the first circle
     }
  }
  if($flag==true){
   if($i!='1'){                       //exclude the first line (title)
       $access_id = "root";
             $db_name   = "inv";
                @ $db = mysql_connect('localhost', $access_id, '831025') or
           die("Could not connect to database.");
          mysql_query("SET NAMES 'GBK'"); //display Chinese
             mysql_select_db($db_name);
    //insert into table test,get data with array data[] from CSV file
    $sql = "insert into test values ('".$data[0]."','".$data[1]."')";
    $result = mysql_query($sql);
   }
     } 
 }
 echo "<script>alert('Import succeed!');</script>";
 fclose($handle);               
 unlink($filename);             
}
?> 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:98029次
    • 积分:1627
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:22篇
    • 译文:0篇
    • 评论:26条
    文章分类