PHP實現csv檔案匯入mysql資料庫的方法

來源:互聯網
上載者:User
這篇文章主要介紹了PHP編程實現csv檔案匯入mysql資料庫的方法,涉及php檔案讀取、轉換、資料庫的串連、插入等相關操作技巧,需要的朋友可以參考下

具體如下:

config.db.php內容如下;

<?php$username="root";$userpass="123";$dbhost="localhost";$dbdatabase="credits2stakes";//產生一個串連$db_connect=mysql_connect($dbhost,$username,$userpass) or die("Unable to connect to the MySQL!");//選擇一個需要操作的資料庫mysql_select_db($dbdatabase,$db_connect);

index.php內容如下:

<meta http-equiv="Content-Type"content="text/html; charset=utf-8" /><form name="frm1" enctype="multipart/form-data" action="insertdb.php" method="post">  <input name="filename" type="file" /><input name="submit" type="submit" value="import" /></form>

insertdb.php內容如下:

<?phpsession_start();header("Content-type:text/html;charset:utf-8");//全域變數$file=$_FILES['filename'];$max_size="2000000"; //最大檔案限制(單位:byte)$fname=$file['name'];$ftype=strtolower(substr(strrchr($fname,'.'),1));//檔案格式$uploadfile=$file['tmp_name'];if($_SERVER['REQUEST_METHOD']=='POST'){   if(is_uploaded_file($uploadfile)){     if($file['size']>$max_size){     echo "Import file is too large";     exit;     }     if($ftype!='csv'){     echo "Import file type is error";     exit;     }   }else{   echo "The file is not empty!";   exit;   }}require("./config.db.php");  //串連mysql資料庫$row=0;$filename=$file['tmp_name'];$handle=fopen($filename,'r');while(!feof($handle) && $data=fgetcsv($handle,1000,',')){  $arr_result=array();  if($row==0){   $row++;   continue;  }  if($row>0 && !empty($data)){    $num=count($data);    for($i=0;$i<$num;$i++){    array_push($arr_result,$data[$i]);   }  //$name = iconv('gb2312','utf-8',$arr_result[1]);  //$sex = iconv('gb2312','utf-8',$arr_result[2]);  $sql="insert into inviter(inviter,invitees,time) value($arr_result[1],$arr_result[2],$arr_result[3])";  //echo $sql;  mysql_query("set names utf8");  $result=mysql_query($sql);  if($result){    echo "插入成功!!!";   }else{    echo "插入失敗!!!";      }   }   $row++;}fclose($handle);?>

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.