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

//将文件另存为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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值